Can a thread lock the object level monitor?

Can a thread lock the object level monitor, If Class level monitor is already locked by another thread?

Please go through the folowing code

publicclass Test1extends Thread{

private String name;

public Test1(String name){ this.name = name;}

publicvoid write(){

System.out.print(name);

try{sleep(300);}catch(InterruptedException ie){}

System.out.print(name);

}

publicstaticvoid main(String[] args){

new Test1("X").start();

new Test1("Y").start();

}

publicvoid run(){

synchronized(Test1.class){

write();

}

}

}

If answer to the above question is YES, how am I getting "XXYY" as output when I run above program...

Thanks in advance...

[1803 byte] By [GourahariDasa] at [2007-11-26 13:01:44]
# 1

What is, or what do you thing is, an "object level monitor"?

You create a thread named X.

You create a thread named Y.

One of these two threads gets control, in this case it's X

X locks Test1

X prints: X

X sleeps 300 milliseconds

X prints: X

X unlocks Test1 and dies.

Now Y can execute.

There is no guarantee that X will run before Y. The output could have been YYXX.

cooper6a at 2007-7-7 17:03:43 > top of Java-index,Core,Core APIs...
# 2

When I synchronize Test1.class (not this) or call a static synchronized method, the class level monitor is locked.

But the object level monitor is stilll free for other threads.

In this case why X is denying Y to enter write() method even though it is a non-static method.

GourahariDasa at 2007-7-7 17:03:43 > top of Java-index,Core,Core APIs...
# 3

There is no relationship between the monitor of a Class object and the monitors of any instances of that class. They are all locked independently.

Your code does not acquire any monitors except that of the Test1 class object. As Cooper6 already pointed out you can see XXYY or YYXX - the scheduling order is not defined. All the locking guarantees you here is that you won't see XYXY or YXYX.

See the FAQ for some good references on learning more about threading and synchronization.

Message was edited by:

davidholmes

davidholmesa at 2007-7-7 17:03:43 > top of Java-index,Core,Core APIs...
# 4

> When I synchronize Test1.class (not

> this) or call a static synchronized method,

> the class level monitor is locked.

> But the object level monitor is stilll free for other

> threads.

> In this case why X is denying Y to enter write()

> method even though it is a non-static method.

Your run() method locks the class object for its entire execution. Once either X or Y has acquired it, then the other can not acquire it until execution of run() has completed.

The fact this is a Class object lock is irrelevent, as long as run() locks the *same* monitor then only one Test1 object will be able to execute its run() method at a time.

davidholmesa at 2007-7-7 17:03:43 > top of Java-index,Core,Core APIs...
# 5
Thanks Cooper6 and davidholmes a lot.
GourahariDasa at 2007-7-7 17:03:43 > top of Java-index,Core,Core APIs...