Master java skills

Static synchronization

Static synchronization is used to synchronized access to a static method. We know static methods doesn’t depend on the objects. Rather, they are called using the class name. That’s why in case of synchronizing static methods, lock isn’t acquired on any objet. Rather, it is acquired on the class.

Important points about static synchronization

  1. Static synchronization acquires lock on the class as opposed to instance synchronization that takes lock on objects.
  2. Static synchronization is used on static methods.
  3. Static and non-static/instance synchronization can work in parallel. Meaning a thread can acquire locks on both, class and object at the same time.

Features of static synchronization

Example without static synchronization

package com.javatrainingschool;

public class Calculation {

	private static int number = 4;

	public static void multiply() {
		for (int i = 1; i < 4; i++) {
			System.out.println(Thread.currentThread().getName() + " : square = " + number * i);
		}

	}
}
package com.javatrainingschool;

public class StaticSynchronizationExample implements Runnable {

	public void run() {
		Calculation.multiply();
	}
	
	public static void main(String[] args) {
		
		Thread t1 = new Thread(new StaticSynchronizationExample());
		Thread t2 = new Thread(new StaticSynchronizationExample());
		
		t1.start();
		t2.start();
	}
}
Output :
Thread-1 : square = 4
Thread-1 : square = 8
Thread-0 : square = 4
Thread-1 : square = 12
Thread-0 : square = 8
Thread-0 : square = 12

As we can see, threads are given chance randomly. They are not synchronized.

Syntax for static synchronization

<access-modifier> synchronized static <retrun-type> <method-name>(<parameters-list>...)

Static synchronization example

package com.javatrainingschool;

public class Calculation {

	private static int number = 4;

	public synchronized static void multiply() {
		for (int i = 1; i < 4; i++) {
			System.out.println(Thread.currentThread().getName() + " : square = " + number * i);
		}

	}
}
package com.javatrainingschool;

public class StaticSynchronizationExample implements Runnable {

	public void run() {
		Calculation.multiply();
	}
	
	public static void main(String[] args) {
		
		Thread t1 = new Thread(new StaticSynchronizationExample());
		Thread t2 = new Thread(new StaticSynchronizationExample());
		
		t1.start();
		t2.start();
	}
}
Output :
Thread-0 : square = 4
Thread-0 : square = 8
Thread-0 : square = 12
Thread-1 : square = 4
Thread-1 : square = 8
Thread-1 : square = 12

In the above results, we can see that first thread-0 finished, then only thread-1 started.