I have a deadlock situation in the code below:
private static final ReadWriteLock opClassesLock = new ReentrantReadWriteLock();
private static final Map<Class<?>, ServiceClass> opClasses = new WeakHashMap<Class<?>, ServiceClass>();
public static ServiceClass get(Class<?> myClass) {
opClassesLock.readLock().lock();
try {
ServiceClass op = opClasses.get(myClass);
if (op == null) {
opClassesLock.writeLock().lock(); // deadlock here
try {
op = new ServiceClass(myClass);
opClasses.put(myClass, op);
} finally {
opClassesLock.writeLock().unlock();
}
}
return op;
} finally {
opClassesLock.readLock().unlock();
}
}
Had I checked the documentation for ReentrantReadWriteLock, I could have predicted this:
Reentrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible.
Besides just using a single lock instead of a read/write-lock (which won't allow concurrent reads), is there any other way to solve this kind of problem?