How to check the monitors on one object?

J

jack

For example

synchronized(myObj) {
......
}

If I can't get myObj synchronized, how do I know which thread holding the lock?

Thanks

Jack
 
H

Harald Hein

jack said:
If I can't get myObj synchronized, how do I know which thread
holding the lock?

If you can't aquire the lock, your thread blocks on the synchronized,
and you can't execute any "who is holding the lock instead" code in
that particular thread.

Since 1.4 Thread has a method to check if the Thread holds a lock.
Using ThreadGroup you could try to find all threads in the VM and check
for every thread before you run into the synchronized. BUT this doesn't
make much sense, too. Since you can't do it under the synchronized
lock, you end up with a small time gap between your test and the
synchronized. During this time gap another thread might aquire the
lock, so any pre-locking test is meaningless.

Welcome to the wounderful world of multi-threading.

And even if you would find out who holds the lock, what do you want to
do with that other thread? There will be a reason why the other thread
holds the lock. And you can't terminate the thread (the API is
deprecated). You could try to interrupt the other thread which might
result in all sorts of things, or nothing (only a status flag is set).

If you need this for debugging purposes only, get a good debugger. If
you can't get one that can list threads and locks, then check your VM.
Most have some key combination that allows to get some dump of threads
and locks out of the VM while it runs.

HH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top