3
3
import com .google .common .cache .CacheBuilder ;
4
4
import com .google .common .cache .CacheLoader ;
5
5
import com .google .common .cache .LoadingCache ;
6
+ import com .google .common .collect .Interner ;
6
7
import org .slf4j .Logger ;
7
8
import org .slf4j .LoggerFactory ;
8
9
20
21
*/
21
22
public class CacheLoaderTest {
22
23
private final static Logger LOGGER = LoggerFactory .getLogger (CacheLoaderTest .class );
23
- private LoadingCache <Long , AtomicLong > loadingCache ;
24
- private final static Long KEY = 1L ;
24
+ private LoadingCache <Integer , AtomicLong > loadingCache ;
25
+ private final static Integer KEY = 1000 ;
25
26
26
27
27
28
private final static LinkedBlockingQueue <Integer > QUEUE = new LinkedBlockingQueue <>(1000 );
@@ -30,29 +31,34 @@ public class CacheLoaderTest {
30
31
private void init () throws InterruptedException {
31
32
loadingCache = CacheBuilder .newBuilder ()
32
33
.expireAfterWrite (2 , TimeUnit .SECONDS )
33
- .build (new CacheLoader <Long , AtomicLong >() {
34
+ .maximumSize (3 )
35
+
36
+ .build (new CacheLoader <Integer , AtomicLong >() {
34
37
@ Override
35
- public AtomicLong load (Long key ) throws Exception {
36
- return new AtomicLong (0L );
38
+ public AtomicLong load (Integer key ) throws Exception {
39
+ return new AtomicLong (0 );
37
40
}
38
41
});
39
42
40
43
41
- for (int i = 0 ; i < 5 ; i ++) {
44
+ for (int i = 10 ; i < 15 ; i ++) {
42
45
QUEUE .put (i );
43
46
}
44
47
}
45
48
46
- private void checkAlert () {
49
+ private void checkAlert (Integer integer ) {
47
50
try {
48
51
52
+ loadingCache .put (integer ,new AtomicLong (integer ));
53
+
54
+ //TimeUnit.SECONDS.sleep(5);
49
55
50
- TimeUnit .SECONDS .sleep (5 );
51
56
52
- LOGGER .info ("当前缓存值={}" , loadingCache .get (KEY ));
57
+ LOGGER .info ("当前缓存值={},缓存大小={}" , loadingCache .get (KEY ),loadingCache .size ());
58
+ LOGGER .info ("缓存的所有内容={}" ,loadingCache .asMap ().toString ());
53
59
loadingCache .get (KEY ).incrementAndGet ();
54
60
55
- } catch (ExecutionException | InterruptedException e ) {
61
+ } catch (ExecutionException e ) {
56
62
LOGGER .error ("Exception" , e );
57
63
}
58
64
}
@@ -70,7 +76,7 @@ public static void main(String[] args) throws InterruptedException {
70
76
break ;
71
77
}
72
78
//TimeUnit.SECONDS.sleep(5);
73
- cacheLoaderTest .checkAlert ();
79
+ cacheLoaderTest .checkAlert (integer );
74
80
LOGGER .info ("job running times={}" , integer );
75
81
} catch (InterruptedException e ) {
76
82
e .printStackTrace ();
0 commit comments