|
| 1 | +package com.crossoverjie.guava; |
| 2 | + |
| 3 | +import com.google.common.cache.CacheBuilder; |
| 4 | +import com.google.common.cache.CacheLoader; |
| 5 | +import com.google.common.cache.LoadingCache; |
| 6 | +import org.slf4j.Logger; |
| 7 | +import org.slf4j.LoggerFactory; |
| 8 | + |
| 9 | +import java.util.concurrent.ExecutionException; |
| 10 | +import java.util.concurrent.LinkedBlockingQueue; |
| 11 | +import java.util.concurrent.TimeUnit; |
| 12 | +import java.util.concurrent.atomic.AtomicLong; |
| 13 | + |
| 14 | +/** |
| 15 | + * Function: |
| 16 | + * |
| 17 | + * @author crossoverJie |
| 18 | + * Date: 2018/6/12 15:33 |
| 19 | + * @since JDK 1.8 |
| 20 | + */ |
| 21 | +public class CacheLoaderTest { |
| 22 | + private final static Logger LOGGER = LoggerFactory.getLogger(CacheLoaderTest.class); |
| 23 | + private LoadingCache<Long, AtomicLong> loadingCache ; |
| 24 | + private final static Long KEY = 1L; |
| 25 | + |
| 26 | + |
| 27 | + private final static LinkedBlockingQueue<Integer> QUEUE = new LinkedBlockingQueue<>(1000); |
| 28 | + |
| 29 | + |
| 30 | + private void init() throws InterruptedException { |
| 31 | + loadingCache = CacheBuilder.newBuilder() |
| 32 | + .expireAfterWrite(2, TimeUnit.SECONDS) |
| 33 | + .build(new CacheLoader<Long, AtomicLong>() { |
| 34 | + @Override |
| 35 | + public AtomicLong load(Long key) throws Exception { |
| 36 | + return new AtomicLong(0L); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + |
| 41 | + for (int i = 0; i < 5; i++) { |
| 42 | + QUEUE.put(i); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private void checkAlert() { |
| 47 | + try { |
| 48 | + |
| 49 | + |
| 50 | + TimeUnit.SECONDS.sleep(5); |
| 51 | + |
| 52 | + LOGGER.info("当前缓存值={}", loadingCache.get(KEY)); |
| 53 | + loadingCache.get(KEY).incrementAndGet(); |
| 54 | + |
| 55 | + } catch (ExecutionException |InterruptedException e ) { |
| 56 | + LOGGER.error("Exception", e); |
| 57 | + } |
| 58 | + } |
| 59 | + public static void main(String[] args) throws InterruptedException { |
| 60 | + CacheLoaderTest cacheLoaderTest = new CacheLoaderTest() ; |
| 61 | + cacheLoaderTest.init(); |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + while (true) { |
| 66 | + |
| 67 | + try { |
| 68 | + Integer integer = QUEUE.poll(200, TimeUnit.MILLISECONDS); |
| 69 | + if (null == integer) { |
| 70 | + break; |
| 71 | + } |
| 72 | + //TimeUnit.SECONDS.sleep(5); |
| 73 | + cacheLoaderTest.checkAlert(); |
| 74 | + LOGGER.info("job running times={}", integer); |
| 75 | + } catch (InterruptedException e) { |
| 76 | + e.printStackTrace(); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + |
| 82 | +} |
0 commit comments