Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When do two two threads block on synchronized static methods?

 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
Eclipse IDE Hibernate Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic