A basic question

J

jack

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?
 
R

Robert Olofsson

jack ([email protected]) wrote:
: 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?

Not from within java, if you care to use a bit of jni and jvmpi you can
do it, but then you might get a "its locked" returned and before you have
decided what to do the lock might have been dropped.

Why do you need it? Why can't you just synchronize and be happy?

/robo
 
G

Gordon Beaton

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/EDU/oswego/cs/dl/util/concurrent/intro.html

/gordon
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top