What I am trying to do is to implement a key-specific read-write lock. Multiple read requests can be executed concurrently if there is no write request on that key. Put requests on different keys can be executed concurrently. I used a ConcurrentHashMap to save the key and keep a record of running write operations for each key.
My code looks like this:
ConcurrentHashMap<String, AtomicInteger> count;
...
...
public void getLock(){
synchronized (count.get(key)) {
while (count.get(key).get() != 0) { // this means there are GET
requests running
try {
count.get(key).wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The idea is that when a new thread wants to read, it needs to first check if there's any write on that key (if the count is not 0) and if not, it can go ahead, if yes, it needs to wait.
So I suppose I have to use count.get(key).wait();
. However, Java forces me to synchronized (count.get(key))
in order to use the wait()
method.
I wonder does it make sense to use the synchronization here since I already use AtomicInteger?
p.s.
I do have notify()
later in the unlock method.