我有一個服務bean,它提供對Map的訪問。有時我需要重建地圖的內容,這需要幾秒鐘的時間,我想在重建時阻止對地圖的訪問,因爲它可以從不同的線程訪問。比while(reentrantLock.isLocked())更好的解決方案等待
@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。 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html – Kiki
爲什麼我們不使用lock.lock(); – matt