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.
As a result, in order to test for correct handling of concurrency. I need to 1. Create the two threads. 2. Start thread 1. 3. As soon as thread 1 owns the monitor, suspend thread 1. 4. Start thread 2. 5. As soon as thread 2 is blocked by thread 1, suspend thread 2. 6. Resume thread 1. 7. Join thread 1. 8. Run some assertions. 9. Resume thread 2. 10. Join thread 2. 11. 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.