private ConcurrentHashMap<Integer, FutureTask<ShopDto> shopTaskMap = new ConcurrentHashMap<Integer, FutureTask<ShopDto>();
public ShopDto loadShop(int shopId) {
ShopDto dto = getFromCache(shopId);
if (dto == null) {
FutureTask<ShopDto> future = shopTaskMap.get(shopId);
if (future == null) {
FutureTask<ShopDto> task = new FutureTask<ShopDto>(new ShopDBTask(shopId));
future = shopTaskMap.putIfAbsent(shopId, task);
if (future == null) {
future = task;
future.run(); //确保本机只有一个线程命中DB
}
}
try {
dto = future.get(200, TimeUnit.MILLISECONDS);
} catch (Exception e) {
return null;
} finally {
shopTaskMap.remove(shopId);
} } //end if (dto == null)
return dto;
}
class ShopDBTask implements Callable<ShopDto>{
private int shopId;
public ShopDBTask (int shopId){
this.shopId = shopId;
}
@Override
public ShopDto call() throws Exception {
ShopDto dto = loadFromDB(shopId);
if(dto == null){
dto = new ShopDto ();
}
setCache(shopId, ShopDto);
return dto;
} }