*
The moose likes Threads and Synchronization and the fly likes When do two two threads block on synchronized static methods? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "When do two two threads block on synchronized static methods?" Watch "When do two two threads block on synchronized static methods?" New topic
Author

When do two two threads block on synchronized static methods?

Faisal syed
Ranch Hand

Joined: Mar 25, 2011
Posts: 35
Hello Fiends,

This is straight out from the Kathy Sierra scjp guide

Threads calling static synchronized methods in the same class will always
block each other—they all lock on the same Class instance
Please illustrate this with a clear example

This is what I tried
This is the class hosting the static method which needs to be safe guarded.

public class StaticSync{


public static void main(String a [] ){
System.out.println("hello world");
}


public static synchronized void method(){
System.out.print("statiic synchronized method");
}


}




// test class
public class StaticSyncTest implements Runnable{

public static void main(String a [] ){

Thread t1 = new Thread(new StaticSyncTest(),"t1");
Thread t2 = new Thread(new StaticSyncTest(),"t2");

t1.start();
t2.start();


}



public void run(){
/// call static sync member from thread
for(int i = 0; i < 100; i ++)
System.out.println(i+"Current thread is "+Thread.currentThread().getName());

StaticSync.method();
}
}

The question is when will 2 invocations of a stataic synchronized methos() block each other???

Thanks
Faisal
lokesh sree
Ranch Hand

Joined: Oct 27, 2009
Posts: 99

Hi Faisal,

Better to use code tags for your example to make it more readable. Also, you didn't tell what output you have got from it and what you have understood from that.
Yes, both your threads t1 and t2 will be using the same lock( lock object of StaticSync class ) when they call StaticSync.method(). However, the method() has no long running code which will clearly demonstrate that other thread is waiting for the lock when first thread is running.
So, my suggestion would be to make StaticSync.method() take lot of execution time.. move that for loop from StaticSyncTest to the method() and notice the behavior of the threads and their locking.


Lokesh
( SCBCD 5, CCENT, SCJP 5 )
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When do two two threads block on synchronized static methods?
 
Similar Threads
Doubt in threads
yield() on synchronized code
Question on Threads?
Thread behavior with synchronized method
Concurrency Question with Thread.sleep(5000) ?