I am looking for a way to combine functionality from synchronized with functionality from java.util.concurrent.locks.ReentrantReadWriteLock. More specifically, I would like one method to lock only if the WriteLock is set, but I want the lock to be on an object variable like synchronized. Here are examples that will help explain:
ReentrantReadWriteLock Example
public void methodOne(String var) {
lock.writeLock().lock;
try {
// Processing
}
finally {
lock.writeLock().unlock();
}
}
public void methodTwo(String var) {
lock.readLock().lock;
try {
// Processing
}
finally {
lock.readLock().unlock();
}
}
In this example, methodTwo can be invoked without blocking as long as the writeLock on methodOne has not been locked. This is good and the functionality I'm looking for, however when the writeLock is locked, it is locked for all cases of var. Instead, I would like for it only to lock on var like with synchronized:
Synchronized Example
public void methodOne(String var) {
synchronized(var) {
// Processing
}
}
public void methodTwo(String var) {
synchronized(var) {
// Processing
}
}
Now, the methods will only block conditional on the input. This is good and and what I'm looking for, however if there are multiple concurrent calls to methodTwo with the same key, they will block. Instead, I would like this to be a "read" style lock and allow the call.
Essentially, I would like a ReadWriteLock that I can synchronize to a variable to obtain both sets of functionality.