让它变得简单:通常 update() 由多个线程执行。一旦这是真的 if(!isSplit && users.size() >= Constants.SPLIT_THRESHOLD) 我希望没有人在 split() 函数被单元格时执行 update() 方法。
public class Cell {
private ConcurrentHashMap<Integer, User> users;
private ConcurrentHashMap<Long, Cell> subCells;
private boolean isSplit;
private Lock splitLock;
public Set<Integer> update(User user){
//code executed by 1 thread
if(!isSplit && users.size() >= Constants.SPLIT_THRESHOLD)
{
splitLock.lock();
{
try
{
split();
isSplit = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
finally
{
splitLock.unlock();
}
}
}
// code executed by multiple threads
// on users hashmap
}
private void merge(){}
private void split(){}
}