【发布时间】:2015-09-29 11:51:11
【问题描述】:
我有一个提供对 Map 的访问的服务 bean。有时我需要重建地图的内容,这需要几秒钟,我想在重建地图时阻止对地图的访问,因为它可以从不同的线程访问。
@Service
public class MyService {
private Map<Key,Value> cache = null;
private ReentrantLock reentrantLock = new ReentrantLock();
public void rebuildCache(){
try {
reentrantLock.lock();
cache = new ConcurrentHashMap<>();
... //processing time consuming stuff and building up the cache
}finally {
reentrantLock.unlock();
}
}
public Value getValue(Key key){
while (lock.isLocked()){}
return cache.get(key);
}
...
}
如你所见,我使用
while (reentrantLock.isLocked()){}
检查锁是否被锁定并等待解锁。这个解决方案似乎很脏。有没有更好的解决方案?
【问题讨论】:
-
看看 FutureTask。 docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
-
我们为什么不使用 lock.lock();
标签: java concurrency locking