In Java, how do I test if an object's monitor is locked? In other words, given a object obj, does any thread own obj's monitor?
I do not care which thread owns the monitor. All I need to test is if ANY thread owns a given object's monitor. Since a thread other than the current thread could own the monitor, Thread.holdsLock( obj ) is not enough as it only checks the current thread.
I am trying to figure the simplest solution possible.
This is not a duplicate because:
- I cannot use higher-level/newer concurrency/locking mechanisms. I cannot use Lock, etc. I must use low-level/old/traditional currency/locking mechanisms such as synchronized, wait(), etc.
- I am not trying to find a time to execute code when has monitor has become unlocked. I am trying to execute code when a monitor is locked. In fact, to give a little bit of background, this part of a unit test where I am trying to start run two threads which both need to lock the same object.
- I cannot call internal private JVM dependent methods such as sun.* .
As a result, in order to test for correct handling of concurrency. I need to
- Create the two threads.
- Start thread 1 .
- As soon as thread 1 owns the monitor, suspend thread 1 .
- Start thread 2 .
- As soon as thread 2 is blocked by thread 1, suspend thread 2 .
- Resume thread 1 .
- Join thread 1 .
- Run some assertions.
- Resume thread 2 .
- Join thread 2 .
- Run some assertions.
What I am trying to figure out is the best way to do #3, primarily, determining when thread 1 owns the monitor.