33import com .google .common .cache .CacheBuilder ;
44import com .google .common .cache .CacheLoader ;
55import com .google .common .cache .LoadingCache ;
6+ import com .google .common .collect .Interner ;
67import org .slf4j .Logger ;
78import org .slf4j .LoggerFactory ;
89
2021 */
2122public class CacheLoaderTest {
2223 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 ;
2526
2627
2728 private final static LinkedBlockingQueue <Integer > QUEUE = new LinkedBlockingQueue <>(1000 );
@@ -30,29 +31,34 @@ public class CacheLoaderTest {
3031 private void init () throws InterruptedException {
3132 loadingCache = CacheBuilder .newBuilder ()
3233 .expireAfterWrite (2 , TimeUnit .SECONDS )
33- .build (new CacheLoader <Long , AtomicLong >() {
34+ .maximumSize (3 )
35+
36+ .build (new CacheLoader <Integer , AtomicLong >() {
3437 @ 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 );
3740 }
3841 });
3942
4043
41- for (int i = 0 ; i < 5 ; i ++) {
44+ for (int i = 10 ; i < 15 ; i ++) {
4245 QUEUE .put (i );
4346 }
4447 }
4548
46- private void checkAlert () {
49+ private void checkAlert (Integer integer ) {
4750 try {
4851
52+ loadingCache .put (integer ,new AtomicLong (integer ));
53+
54+ //TimeUnit.SECONDS.sleep(5);
4955
50- TimeUnit .SECONDS .sleep (5 );
5156
52- LOGGER .info ("当前缓存值={}" , loadingCache .get (KEY ));
57+ LOGGER .info ("当前缓存值={},缓存大小={}" , loadingCache .get (KEY ),loadingCache .size ());
58+ LOGGER .info ("缓存的所有内容={}" ,loadingCache .asMap ().toString ());
5359 loadingCache .get (KEY ).incrementAndGet ();
5460
55- } catch (ExecutionException | InterruptedException e ) {
61+ } catch (ExecutionException e ) {
5662 LOGGER .error ("Exception" , e );
5763 }
5864 }
@@ -70,7 +76,7 @@ public static void main(String[] args) throws InterruptedException {
7076 break ;
7177 }
7278 //TimeUnit.SECONDS.sleep(5);
73- cacheLoaderTest .checkAlert ();
79+ cacheLoaderTest .checkAlert (integer );
7480 LOGGER .info ("job running times={}" , integer );
7581 } catch (InterruptedException e ) {
7682 e .printStackTrace ();
0 commit comments