开发者

Need to know object locking information

In java, I have created an object with global scope.

At some point I am in a diff开发者_运维技巧erent thread and need to know whether the global object is currently locked by any threads.

  • Krishna


This is not possible using the synchronized keyword on ordinary Objects.

You need a "lock" object, perhaps one implementing java.lang.concurrent.locks.Lock, which offers a tryLock() method or similar.

This allows your thread to attempt to acquire the lock, returning true if the Lock is not currently locked elsewhere.

Of course, in this case, you may then need to unlock the lock immediately - otherwise your thread will prevent other threads from making progress.


The big problem here is defining 'currently'.

The best I can suggest is to try to acquire the lock with a zero timeout. If you get the lock, you are sure that the global object is locked - by your 'different thread'. If not, the object may be locked or not by some other thread, probably it is, but the lock may have been released while your failed lock attempt was returning. You should be able to get more reliable results if you raise the priority of your 'different thread' to the highest possible during your lock attempt.

If this test is for some temporary debugging, optimization or statistical purpose then fine, but you should not use anything like this to implement deliverable functionality.

Rgds, Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜