[concurrency-interest] when to use lock and when
touselockInterruptibly
Dawid Kurzyniec
dawidk at mathcs.emory.edu
Thu Dec 1 12:28:50 EST 2005
Peter Veentjer - Anchor Men wrote:
>With a lock() you always get the lock? What if the thread is interrupted
>while it wants to acquire a lock with the lock() method. What is going
>to happen? With a lockInterruptibly() a InterruptedException is thrown.
>But what happens with a normal lock() method?
>
>
>
Essentially, nothing - at least until the lock is obtained, and some
operation later tests the status of the interruption flag. Interrupting
a thread merely sets the "interrupted" status flag to true; whether and
when the thread responds to interruption is up to that thread. Certain
methods, like Object.wait(), Thread.sleep(), Lock.lockInterruptibly(),
and Condition.await(), are responsive to interruption, and will throw
InterruptedException if the "interrupted" flag is set upon invocation or
becomes set while the thread is blocked. In other situations, e.g. if a
thread is blocked on "synchronized", lock.lock(),
Condition.awaitUninterruptibly(), or I/O operation, or simply if is not
blocked at all, the interruption requests do not cause any immediate
action except for setting the flag.
Basically, lock.lock() cannot complete in any other way than
successfully obtaining the lock; the only other way is to kill the JVM.
Regards,
Dawid
More information about the Concurrency-interest
mailing list