Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 10 instances of a class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.
If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock.
Methods: Thread can acquire the lock at a class level by two methods namely
- Using the synchronized static method.
- Using synchronized block.
Method 1: Using the synchronized static method
Implementation: We have a Geek class. We want to use static synchronization method of this class, as soon as the thread entered the synchronized method, the thread acquires the lock at the class level, rest of the threads wait to get the class monitor lock. The thread will leave a lock when it exits from the synchronized method.
public static synchronized int incrementCount()
{
}
Example
Java
// Java program to illustrate class level lock
// Main Class
// Implememnting the Runnable interface
class Geek implements Runnable {
// Method 1
// @Override
public void run() { Lock(); }
// Method 2
// Method is static
public static synchronized void Lock()
{
// Gwetting the name of current thread by using
// getName() method to get name of the thread and
// currentThread() to get the current thread
System.out.println(
Thread.currentThread().getName());
// class level lock
synchronized (Geek.class)
{
System.out.println(
"in block "
+ Thread.currentThread().getName());
System.out.println(
"in block "
+ Thread.currentThread().getName()
+ " end");
}
}
// Method 3
// Main driver method
public static void main(String[] args)
{
// Creating an object of above class
// in the main() method
Geek g1 = new Geek();
// Sharing the same object across two Threads
// Creating an object of thread class where
// t1 takes g1
Thread t1 = new Thread(g1);
// Creating an object of thread class where
// t2 takes g1
Thread t2 = new Thread(g1);
// Creating second object of above class
// in the main() method
Geek g2 = new Geek();
// Creating an object of thread class where
// t3 takes g2
Thread t3 = new Thread(g2);
// setName() method is used to set name to the
// thread
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
// start() method is used for initiating the current
// thread
t1.start();
t2.start();
t3.start();
}
}
Outputt1
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 entered the static synchronized method and was holding a lock on Geek's class. So, the rest of the threads waited for Thread t1 to release the lock on Geek's class so that it could enter the static synchronized method.
Method 2: Using synchronized block method
Implementation: We have a "Geek" class. We want to create a synchronization block and pass class name. class as a parameter tells which class has to synchronized at the class level. As soon as the thread entered the synchronized block, the thread acquire the lock at class, rest of the threads wait to get the class monitor lock. The thread will leave lock when it exits from the synchronized block.
synchronized (Geek.class) {
//thread has acquired lock on Geek class
}
Example
Java
// Java program to illustrate class level lock
// Main Class
// It is implementing the Runnable interface
class Geek implements Runnable {
// Method 1
// @Override
public void run()
{
// Acquire lock on .class reference
synchronized (Geek.class)
// ClassName is name of the class containing method.
{
{
System.out.println(
Thread.currentThread().getName());
System.out.println(
"in block "
+ Thread.currentThread().getName());
System.out.println(
"in block "
+ Thread.currentThread().getName()
+ " end");
}
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating an object of above class
// in the main() method
Geek g1 = new Geek();
// Creating an object of thread class i.e Thread
// 1 where t1 takes g1 object
Thread t1 = new Thread(g1);
// Here, creating Thread 2 where t2 takes g1
// object
Thread t2 = new Thread(g1);
// Creating another object of above class
// in the main() method
Geek g2 = new Geek();
// Now Creating Thread 3 where t3 takes g2 object
Thread t3 = new Thread(g2);
// Ginving custom names to above 3 threads
// using the setName() method
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
// start() method is used to begin execution of
// threads
t1.start();
t2.start();
t3.start();
}
}
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 entered synchronized block and was holding the lock on 'Geek' class. So, the rest of the threads waited for Thread t1 to release the lock on the 'Geek' class so that it could enter the synchronized block.
Similar Reads
Object Level Lock in Java
Every object in Java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. An object-level lock is a mechanism when we want to synchronize a non-static method or non-static code block such that only one thread will be able to execute
3 min read
Object level and Class level locks in Java
Synchronization: Synchronization is a modifier that is used for the method and blocks only. With the help of a synchronized modifier, we can restrict a shared resource to be accessed only by one thread. When two or more threads need access to shared resources, there is some loss of data i.e. data in
3 min read
Object Class in Java
Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
7 min read
LinkedBlockingQueue Class in Java
The LinkedBlockingQueue in Java is part of the java.util.concurrent package and implements the BlockingQueue interface. It provides a thread-safe, bounded, or unbounded queue used for managing tasks in a producer-consumer scenario. This queue can be used in multithreaded environments where one threa
8 min read
Nested Classes in Java
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
5 min read
Local Inner Class in Java
Prerequisites: Nested Classes in Java Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block the
5 min read
Java.lang.ThreadLocal Class in Java
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing im
4 min read
Static class in Java
Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
3 min read
ReentrantReadWriteLock Class in Java
ReentrantReadWriteLock class of Java is an implementation of ReadWriteLock, that also supports ReentrantLock functionality. The ReadWriteLock is a pair of associated locks, one for read-only operations and one for writing. Whereas, the ReentrantLock is a re-entrant mutual exclusion Lock with the sam
5 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is
3 min read