LocalCache 缓存设置

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);
		}
		
		
		
		

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值