import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; /** * 本地缓存帮助类 * * @author ThinkPad * */ public class LocalCache<K, V> { public Cache<K, V> cache = callableCached(); /** * 定时任务map */ private ConcurrentHashMap<Object, Timer> timerMap = new ConcurrentHashMap<Object, Timer>(); public Cache<K, V> callableCached() { Cache<K, V> cache = CacheBuilder.newBuilder().build(); return cache; } public LocalCache() { } public LocalCache(Cache<K, V> cache) { this.cache = cache; } /** * 加入定時任務,定时任务只会初始化一次 * * @param ObjectKey * @param timerTask * @param delay * @param period * @return */ public void addTimerTask(String ObjectKey, TimerTask timerTask, long delay, long period) { if (ObjectKey == null || timerTask == null) { return; } if (!timerMap.containsKey(ObjectKey)) { Timer timer = new Timer(); Timer timerOld = timerMap.putIfAbsent(ObjectKey, timer); if (timerOld == null) { timer.schedule(timerTask, delay, period); } } return; } /** * 关闭定时任务 * * @param ObjectKey */ public void cancelTimerTask(String ObjectKey) { if (ObjectKey == null) { return; } Timer timer = timerMap.get(ObjectKey); if (timer != null) { timerMap.remove(ObjectKey); timer.cancel(); } } public static void main(String[] args) throws Exception { final LocalCache<String, String> cache = new LocalCache<String, String>(); System.out.println(cache.cache.get("1", new Callable<String>() { public String call() throws Exception { Thread.sleep(1000); return "3"; } })); for( int i=0;i<10;i++){ final int j = i; new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { cache.addTimerTask("1", new TimerTask() { @Override public void run() { cache.cache.put("1", j+""+new Random().nextInt(40)); } }, 1, 1000); } catch (Exception e) { e.printStackTrace(); } } }).start();; } //cache.cache.put("1", "2"); while(true){ System.out.println(cache.cache.get("1", new Callable<String>() { @Override public String call() throws Exception { // TODO Auto-generated method stub Thread.sleep(1000); return "3"; } })); Thread.sleep(1000); } } }
LocalCache 缓存设置
猜你喜欢
转载自m635674608.iteye.com/blog/2380993
今日推荐
周排行