VOOZH about

URL: https://www.geeksforgeeks.org/java/class-level-lock-in-java/

⇱ Class Level Lock in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Class Level Lock in Java

Last Updated : 17 Mar, 2026

Class level lock is a lock on the Class object, used when working with static synchronized methods or blocks. Only one thread can execute any static synchronized code of a class at a time, regardless of number of objects.
It is mainly used to protect shared static data.

  • Lock is applied on the class, not on objects (common for all instances).
  • Achieved using static synchronized methods or synchronized(ClassName.class) block.
  • Ensures only one thread executes static synchronized code at a time.

Methods of Class Level Lock

1. Using the synchronized static method

This method automatically acquires the class-level lock when a thread enters it. Only one thread can execute any static synchronized method of the class at a time.

  • Lock is on ClassName.class
  • Applied directly using static synchronized
  • Simple and automatic locking

Output
t1
in block t1
in block t1 end
t3
in block t3
in block t3 end
t2
in block t2
in block t2 end

2. Using synchronized block method 

This method uses a block where the class object is explicitly locked using ClassName.class. It allows better control by synchronizing only specific code. 

  • Lock is on ClassName.class
  • Uses synchronized(ClassName.class)
  • More flexible than method-level synchronization.

Output:

t1
in block t1
in block t1 end
t3
in block t3
in block t3 end
t2
in block t2
in block t2 end

Output explanation: Thread t1 acquired the class lock by entering the synchronized block. Other threads waited until t1 released the lock

Comment