Class-Level Locking in Java: Ensuring Thread Safety at the Class Level
In Java, class-level locking, also known as static synchronization, is a synchronization mechanism that ensures thread safety at the class level.
Unlike object-level locking, where each object has its intrinsic lock, class-level locking works on the class itself and prevents multiple threads from concurrently executing synchronized static methods.
When a thread acquires the class-level lock, it gains exclusive access to all synchronized static methods of that class.
This means that while a thread is executing a synchronized static method, other threads are blocked from accessing any synchronized static methods of the same class.
Example: Implementing Class-Level Locking
Let's illustrate class-level locking with a simple example.
Consider a shared Counter
class that contains a static synchronized method called increment()
:
public class Counter {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static int getCount() {
return count;
}
}
In this example, the increment() method is a static synchronized method. This means that regardless of the number of instances of the Counter class, only one thread can execute the increment() method at a time across all instances.
Creating Multiple Threads:
Now, let's create multiple threads to simulate concurrent increment operations:
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 10000; i++) {
Counter.increment();
}
};
int numThreads = 4;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
// Wait for all threads to complete
try {
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Count: " + Counter.getCount());
}
}
In this example, we create four threads, and each thread increments the shared Counter using the increment() method 10,000 times.
Thanks to the class-level locking of the increment() method, only one thread can execute it at a time. As a result, the final count value will be equal to the number of threads multiplied by the number of increments per thread (4 * 10000 = 40000).
Conclusion:
Class-level locking in Java is a powerful mechanism to achieve thread-safety at the class level. By synchronizing static methods, you can ensure that multiple threads safely interact with static variables and shared resources without causing data corruption or race conditions. Class-level locking is essential for building robust, concurrent Java applications that require thread-safe operations across multiple instances of a class.
0 Comments