diff --git a/CHANGE.md b/CHANGE.md index b1fe8e8c..3bffe1a7 100644 --- a/CHANGE.md +++ b/CHANGE.md @@ -735,4 +735,6 @@ * 2016-07-22 - + weixin4j-base:主要调整退款相关类与官网一致 \ No newline at end of file + + weixin4j-base:主要调整退款相关类与官网一致 + + + weixin4j-base:获取cache时加锁处理(via 风车车) \ No newline at end of file diff --git a/weixin4j-base/src/main/java/com/foxinmy/weixin4j/cache/CacheManager.java b/weixin4j-base/src/main/java/com/foxinmy/weixin4j/cache/CacheManager.java index 808bca27..ff9d9485 100644 --- a/weixin4j-base/src/main/java/com/foxinmy/weixin4j/cache/CacheManager.java +++ b/weixin4j-base/src/main/java/com/foxinmy/weixin4j/cache/CacheManager.java @@ -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 { protected final CacheCreator cacheCreator; protected final CacheStorager cacheStorager; + private final ReentrantLock lock = new ReentrantLock(); public CacheManager(CacheCreator cacheCreator, CacheStorager cacheStorager) { @@ -30,9 +34,20 @@ public class CacheManager { public T getCache() throws WeixinException { String cacheKey = cacheCreator.key(); T cache = cacheStorager.lookup(cacheKey); - if (cache == null) { - cache = cacheCreator.create(); - cacheStorager.caching(cacheKey, cache); + 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; }