On 1 Jul 2003 10:11:04 -0700, jack wrote:
> I have one basic java question, but seems may not have answer.
>
> How do I check the monitor of one object?
>
> For example
>
> synchronized(myobj) {
>
> mystatmenet
>
> }
>
> If I can't go to mystatemnet, means I can't get the lock of myobj, but
> before I call synchronized(myobj), can I check whether it is locked,
> and which thread is locking it?
No. The monitor can only be used to deny or grant access to a section
of code. But you can use that to build more complex types of
synchronization if you need it. Here is an extremely simple, untested
example:
public class Mutex {
private boolean taken;
Thread owner;
public Mutex() {
taken = false;
owner = null;
}
public void synchronized lock() {
while (taken) {
wait();
}
taken = true;
owner = Thread.currentThread();
}
public void synchronized unlock() {
if (owner == Thread.currentThread()) {
taken = false;
owner = null;
notify();
}
}
public boolean synchronized tryLock() {
if (taken) {
return false;
}
else {
taken = true;
owner = Thread.currentThread();
return true;
}
}
public boolean synchronized isLocked() {
return taken;
}
public Thread synchronized owner() {
return owner;
}
}
To get the functionality you want, create an instance of Mutex and
synchronize uting its methods instead. If you need to test before
taking a lock (in order to avoid blocking, or something) then you
can't test and lock separately, use tryLock() for that.
For more and better examples, see:
http://gee.cs.oswego.edu/dl/classes/...ent/intro.html
/gordon
--
[ do not send me private copies of your followups ]
g o r d o n . b e a t o n @ e r i c s s o n . c o m