Re: About multithreading
418928@cepsz.unizar.es wrote On 11/02/06 13:24,:
Hi everybody,
I'd like to know if there is any way to know which execution thread
holds a lock.
synchronized(obj) {
System.out.println(Thread.currentThread()
+ " holds the lock on " + obj);
}
Not very useful for your purposes, but I think that's the
only reliable way ...
The problem with "Who owns the lock?" queries is that
the result can be out of date before you can use it. All
you could really get (and I don't know whether even this
much is Javapossible) is "Who owned the lock a moment ago?"
This tells you very little about who owns the lock now
(for some definition of "now"), or about how many times the
lock has been taken and released since you asked about it.
There might be a way to find out whether the current
thread does or doesn't hold a particular lock, and that
result would be "stable:" if you don't seize or release the
lock between the moment of the query and the moment you
make a decision based on it, the result remains valid. And
if the result happens to be "I've got it," you know that no
other thread has it. But if the result is "No, not mine"
then there's nothing you can conclude about the state of
the other threads in the program.
That is, I would like to know, before a block
synchronized(o), if any other thread holds the lock to o (for
debugging, for example, because I think that no other thread should
have the lock at that moment). I think it's not possible, not even with
the new ReentrantLocks, but just in case you may have any suggestion to
debug these kind of things...
You could (hypothetically) check a lock and find that
nobody owned it, but that still wouldn't tell you much about
the correctness of the program. It's not a matter of whether
the lock is or isn't held at a moment when you think it should
be free, but of whether there's a path by which another thread
*can* attempt to take the lock when it shouldn't. Poor analogy:
If you never look at the traffic signals, the fact that the
light happens to be green when you drive through the intersection
doesn't mean you're driving correctly.
--
Eric.Sosman@sun.com