Sobes.tech
Junior — Middle

What is the difference between synchronized instance methods and static synchronized methods in Java?

sobes.tech AI

Answer from AI

In Java, synchronized methods come in two types: instance synchronized methods and static synchronized methods. The main difference lies in which object the lock is on:

  • Instance synchronized method (synchronized without static): The lock is on the object (this) that owns the method. This means that if you have multiple instances of a class, each has its own lock.

  • Static synchronized method (static synchronized): The lock is on the class object — the Class object representing the class itself. Thus, the lock is shared among all instances of the class.

Example:

public class Example {
    public synchronized void instanceMethod() {
        // locks on this
    }

    public static synchronized void staticMethod() {
        // locks on Example.class
    }
}

This means that two threads cannot execute the same instance synchronized method of the same object simultaneously, but they can execute synchronized methods of different objects of this class.

At the same time, a static synchronized method locks the class as a whole, so only one thread can execute any static synchronized method of this class at a time, regardless of the instances.

What is the difference between synchronized instance… - sobes.tech