We use code that uses syncronized blocks around segments of code with a lot of wait and notifyAll() calls. We are trying to convert these to use Java 5 Lock.lock() and Lock.unlock() methods. How do I migrate this code to remove all the wait and notifyAll calls. I do not know the equivalent to these using the new Locking features.
Any links with examples would be appreciated.
Thanks in Advance
Eq., the following code needs to be converted to use Lock.lock() and lock.unlock The first part to remove the synchronized block is simple as I just need to call lock() method. The question is what can be done for the notifyAll() and wait methods.
synchronized( LOCK ) { while( !Thread.interrupted() ) { try { working = runRules(); if( !working ) LOCK.notifyAll(); LOCK.wait( working ? shortTimeout : longTimeout ); } catch( final InterruptedException e ) { Package.log.info( "Thread was interrupted. Exiting.", e ); return; } } }
ReentrantLock
s are more error-prone thansynchronized
blocks - it is easy to miss thefinally
block. So unless you need some specific feature -lockInterruptibly
ortryLock
- there is no point in converting the code. If you are determined to migrate the code to newer APIs, you should consider restructuring the code to use higher-level APIs likeSemaphore
s,Latch
es orBarrier
s. – Binil Thomas