【发布时间】:2015-07-05 10:07:38
【问题描述】:
服务必须将数据缓存在内存中并将数据保存在数据库中。 getAmount(id) 检索当前余额或为零,如果之前未调用 addAmount() 方法
指定的标识。如果第一次调用方法,addAmount(id, amount) 会增加余额或设置。服务必须是线程安全的。线程安全是我的实现吗?可以做哪些改进?
public AccountServiceImpl() {
cache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.HOURS)
.concurrencyLevel(4)
.maximumSize(10000)
.recordStats()
.build(new CacheLoader<Integer, Account>() {
@Override
public Account load(Integer id) throws Exception {
return new Account(id, accountDAO.getAmountById(id));
}
});
}
public Long getAmount(Integer id) throws Exception {
synchronized (cache.get(id)) {
return cache.get(id).getAmount();
}
}
public void addAmount(Integer id, Long value) throws Exception {
Account account = cache.get(id);
synchronized (account) {
accountDAO.addAmount(id, value);
account.setAmount(accountDAO.getAmountById(id));
cache.put(id, account);
}
}
}
【问题讨论】:
标签: java multithreading caching