javasynchronization

Java synchronized and static synchronized method accessing static field


What would be the behaviour of the following program where static synchronized method and instance synchronized method is trying to access static field of same class in different threads? Will any thread get blocked? It's very confusing.

class MyClass
{
        public static int i = 5;

        public synchronized void m1()
        {
                System.out.println(i); //uses static field i of MyClass
            //T1 is executing this method
        }

        public static synchronized void m3()
        {
            //T2 will be able to call this method on same object lock while it is using
            //static field i???
            System.out.println(i);//uses static field i of MyClass
        }
}

Solution

  • Synchronized instance methods are equivalent of

    public void m1() {
        synchronized(this) {
            ...
        }
    }
    

    (well, they are not exactly the same, but the answer to your question does not suffer from that difference).

    Synchronized static methods are synchronized on the class:

    public void m2() {
        synchronized(MyClass.class) {
            ...
        }
    }
    

    As you can see, two block are synchronized on difference objects: m1 is synchronized on the instance it is called on, and m2 is synchronized on the instance of Class<MyClass> which represents your class in JVM. So those two methods can be called without blocking each other.