lets make it simple: normally update() is executed by multiple threads. once this is true if(!isSplit && users.size() >= Constants.SPLIT_THRESHOLD) i want that no one is executiong the update() method when the split() functions is celled.
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(){}
}
I'm not in a position to tell you if your code is currently getting the locking / synchronization correct.
However, under normal circumstances, I'd use a primitive object mutex for something like this:
private final Object splitLock = new Object();
// Use it like this ...
synchronized (splitLock) {
split();
}
AFAIK, there is no performance advantage in using a ReentrantLock
over a primitive object mutex. I'd only recommend using this class if you are going to make use of features that primitive object mutexes don't support;