Static Synchronization In Java
Static Synchronization
In Java, if we create any static method as synchronized, the lock will be on the class and not on the object.
Without static synchronization
Assume that, there are two objects of a shared class named a1 and a2. In case of synchronized method and synchronized block, here cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object, which have a single lock. There can be an interference between t1 and t3 or t2 and t4 because t1 gets another lock and t3 gets another lock and if we want no interference between t1 and t3 or t2 and t4 that time, we need to use static synchronization. Static synchronization solves these types of problems in Java.
Let’s see an example: with static synchronization, given below.
Code
- class C {
- synchronized static void print(int n) {
- for (int i = 1; i <= 4; i++) {
- System.out.println(n * i);
- try {
- Thread.sleep(1500);
- } catch (Exception e) {}
- }
- }
- }
- class Thread1 extends Thread {
- public void run() {
- C.print(10);
- }
- }
- class Thread2 extends Thread {
- public void run() {
- C.print(100);
- }
- }
- class Thread3 extends Thread {
- public void run() {
- C.print(1000);
- }
- }
- public class StaticSynchronization {
- public static void main(String t[]) {
- Thread1 t1 = new Thread1();
- Thread2 t2 = new Thread2();
- Thread3 t3 = new Thread3();
- t1.start();
- t2.start();
- t3.start();
- }
- }
Output
In the example, shown above, we apply synchronized keyword on the static method to execute static synchronization.
Let’s see an example with annonynmous class.
Code
- class C {
- synchronized static void print(int n) {
- for (int i = 1; i <= 4; i++) {
- System.out.println(n * i);
- try {
- Thread.sleep(1500);
- } catch (Exception e) {}
- }
- }
- }
- public class StaticSynchronization {
- public static void main(String[] args) {
- Thread t1 = new Thread() {
- public void run() {
- C.print(10);
- }
- };
- Thread t2 = new Thread() {
- public void run() {
- C.print(100);
- }
- };
- Thread t3 = new Thread() {
- public void run() {
- C.print(1000);
- }
- };
- t1.start();
- t2.start();
- t3.start();
- }
- }
Output
In the example, shown above, we use anonymous class to create threads.
Synchronized block on a class lock
The synchronized block synchronizes on the lock of the object indicated by the reference .class name .class and a static synchronized method print(int n) in class C is equal to the declaration, given below.
static void print(int n) {
synchronized (C.class) {
// ... code
}
}
Summary
Thus, we learnt that in Java, if we create any static method as synchronized, the lock will be on the class not on the object and also learnt how we can create it in Java.