我有類似的代碼如下:同步上兩個或多個對象(爪哇)
public class Cache{
private final Object lock = new Object();
private HashMap<Integer, TreeMap<Long, Integer>> cache =
new HashMap<Integer, TreeMap<Long, Integer>>();
private AtomicLong FREESPACE = new AtomicLong(102400);
private void putInCache(TreeMap<Long, Integer> tempMap, int fileNr){
int length; //holds the length of data in tempMap
synchronized(lock){
if(checkFreeSpace(length)){
cache.get(fileNr).putAll(tmpMap);
FREESPACE.getAndAdd(-length);
}
}
}
private boolean checkFreeSpace(int length){
while(FREESPACE.get() < length && thereIsSomethingToDelete()){
// deleteSomething returns the length of deleted data or 0 if
// it could not delete anything
FREESPACE.getAndAdd(deleteSomething(length));
}
if(FREESPACE.get() < length) return true;
return false;
}
}
putInCache
由大約139螺紋的第二調用。我可以確定這兩種方法在cache
和FREESPACE
之間會同步嗎?另外,checkFreeSpace()
多線程安全,即我可以確定一次只能調用一次該方法嗎?這段代碼的「多線程安全性」可以改進嗎?
(在該代碼中使用'AtomicLong'沒有意義。) – 2009-11-27 17:31:52