This is TOO old, but I was reviewing the code of a Junior coleague today and I found a huge bug related to used a Java Lock object like if it was a synchronized block. I was looking for some documentation about Java synchronized not being perfect and just came across this and thought about leaving the solution I have the guy:
In the case of synchronized, it really depends on your logic, since java guarantees the liberation of the lock.
However, when you use Object based locks, like java's ReentrantLock, you must allways do the following:
private final ReentrantLock lock = new ReentrantLock ();
void foo() {
lock.lock();
try {
// Do your things
} finally {
lock.unlock();
}
}
Once you have this structure to ensure lock liberation, you can either encapsulate both the lock and the whole try/finally into another try if you wasnt to handle the catch ourside the lock, or puit it where // Do your things is if you want to handle it from inside.
Also, keep in mind that java locks are not perfect, and like in any programming languaje, the choice of the type of the lock depends on the underlying languaje, how critical the operation is (will someone die if the lock fails, or a controlled software retry once in a million times will do the trick?) and the performance impact of the lock.
If you know nothing about locks, I'd recomend learning the following concepts:
- Monitor (synchronization)
- Mutual exclusion
- Read/write lock pattern
- Read-copy-update
- Semaphore (programming)
Most of the time, what you really need is either a semaphore a multiread singlewrite lock or just a monitor, so knowing the terms will let you search for what you need much faster.
Then if you do need to do operations in the catch section...these wouldn't block other threads.
Why would we give up the lock due to an exception? – Ac