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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read