Java -- Lock Testing and Timeouts

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值