public class ReaderWriterLock
extends java.lang.Object
ReaderWriterLock is a locking mechanism that allows several readers to access a resource simultaneously
but only single writer. When writer has locked the resource neither readers nor other writers are allowed
acces until the resource has been released by the writer who has the lock. Also writer will not get a lock
if a reader or some other writer has the lock. This lock operates with the writers-first principle meaning
that if a writer is waiting for the lock, no more readers are allowed to get the lock. When you get a lock
(and the get*Lock method returns true) you should always put the following code inside a try block and release
the lock in the finally block after the try. This will ensure that the lock is released, even if an exception is
thrown and not handled. If you fail to release the lock, your application will most likely get stuck.
Note that if the same thread tries to get a second writer lock, the thread will get blocked indefinitely and
also block any other threads trying to use this lock. This behavior is somewhat different than synchronized
blocks in java which will get a lock for the executing thread to the specified object's monitor if, it does
not have that allready.
Take care that you release exactly as many locks as you acquire. If you release more, a RuntimeException
will be thrown and if you release less, others won't be able to get the lock.
- Author:
- olli