This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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

Win a copy of Java 8 in Action this week in the Java 8 forum!
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

When do two two threads block on synchronized static methods?

Faisal syed
Ranch Hand

Joined: Mar 25, 2011
Posts: 33
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");



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());


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

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.

I agree. Here's the link:
subject: When do two two threads block on synchronized static methods?
Similar Threads
Doubt in threads
Question on Threads?
Thread behavior with synchronized method
Concurrency Question with Thread.sleep(5000) ?
yield() on synchronized code