weixin4j-base:获取cache时加锁处理(via 风车车)

This commit is contained in:
jinyu 2016-07-22 14:04:33 +08:00
parent 42a3fc357e
commit 6c00f26e13
2 changed files with 21 additions and 4 deletions

View File

@ -736,3 +736,5 @@
* 2016-07-22
+ weixin4j-base:主要调整退款相关类与官网一致
+ weixin4j-base:获取cache时加锁处理(via 风车车)

View File

@ -1,5 +1,8 @@
package com.foxinmy.weixin4j.cache;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import com.foxinmy.weixin4j.exception.WeixinException;
/**
@ -14,6 +17,7 @@ import com.foxinmy.weixin4j.exception.WeixinException;
public class CacheManager<T extends Cacheable> {
protected final CacheCreator<T> cacheCreator;
protected final CacheStorager<T> cacheStorager;
private final ReentrantLock lock = new ReentrantLock();
public CacheManager(CacheCreator<T> cacheCreator,
CacheStorager<T> cacheStorager) {
@ -30,10 +34,21 @@ public class CacheManager<T extends Cacheable> {
public T getCache() throws WeixinException {
String cacheKey = cacheCreator.key();
T cache = cacheStorager.lookup(cacheKey);
try {
if (cache == null && lock.tryLock(3, TimeUnit.SECONDS)) {
try {
cache = cacheStorager.lookup(cacheKey);
if (cache == null) {
cache = cacheCreator.create();
cacheStorager.caching(cacheKey, cache);
}
} finally {
lock.unlock();
}
}
} catch (InterruptedException e) {
throw new WeixinException("get cache error on lock", e);
}
return cache;
}