0

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

At some point I am in a different thread and need to know whether the global object is currently locked by any threads.

  • Krishna

2 Answers 2

2

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.