A Thread blocks indefinitely when it calls the "lock" method to acquire a lock that is owned by another thread. You can be more cautious about acquiring a lock. The "tryLock" method tries to acquire a lock and return "true" if it was successful. Otherwise, it immediately returns "false", and the thread can go off and do something else.
if (myLock.tryLock()) {
//now the thread owns the lock
try {... ...}
finally { myLock.unlock(); }
} else
// do something else
You can call "tryLock" with a timeout parameter, like this:
if (myLock.tryLock(100, TimeUnit.MILLISECONDS) ... ...
"TimeUnit" is an enumeration with values "SECONDS", "MILLISECONDS", "MICROSECONDS", and "NANOSECONDS".
The "lock" method can not be interrupted. If a thread is interrupted while it is waiting to acquire a lock, the interrupted thread continues to be blocked until the block is available. If a "deadlock" occurs, then the "lock" method can never terminate.
However, if you call "tryLock" with a timeout, an "InterruptedException" is thrown if the thread is interrupted while it is waiting. This is a clearly useful feature because it allows a program to break up deadlocks.
You can also call "lockInterruptibly" method. It has the same meaning as "tryLock" with an infinite timeout.
When you wait on a condition, you can alse supply a timeout:
myCondition.await(100, TimeUnit.MILLISECONDS)
The "await" method returns if another thread has activated this thread by calling "signal" or "signalAll", or if the timeout has elapsed, or if the thread was interrupted.
The "await" methods throw an "InterruptedException" if the waiting thread is interrupted.
Use "awaitUninterruptibly" method instead of the "await" method can keep waiting even if it has been interrupted.