Java – Class Level Lock | Code Factory


Index Page : Link

Donate : Link

Medium Link : Link

Applications : Link

  • 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 thread required class level lock.
  • Once thread got class level lock then it is allow to execute any state Synchronized method of that class.
  • Once method execution completes automatically thread release a lock.
  • While a thread executing static Synchronized method the remaining threads are not allowed to execute any static Synchronized of that class simultaneously. But remaining threads are allow to execute the following methods simultaneously.
  1. normal static methods
  2. synchronized instance methods
  3. normal instance methods
public class X {
	static synchronized m1()
	static synchronized m2()
	static m3()
	static m4()
	m5()
}
package com.example.thread;

/**
 * @author code.factory
 *
 */
public class SynchronizedTest {
	public static void main(String... args) {
		Display d = new Display();
		MyThread1 t1 = new MyThread1(d);
		MyThread2 t2 = new MyThread2(d);
		t1.start();
		t2.start();
	}
}

class Display {
	public synchronized void displayI() {
		for(int i=1; i<=5; i++) {
			System.out.println(i);
			try {
				Thread.sleep(1000);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public synchronized void displayJ() {
		for(int j=6; j<=10; j++) {
			System.out.println(j);
			try {
				Thread.sleep(1000);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}

class MyThread1 extends Thread {
	Display d;
	public MyThread1(Display d) {
		this.d = d;
	}
	public void run() {
		d.displayI();
	}
}

class MyThread2 extends Thread {
	Display d;
	public MyThread2(Display d) {
		this.d = d;
	}
	public void run() {
		d.displayJ();
	}
}

Output :

1
2
3
4
5
6
7
8
9
10

2 thoughts on “Java – Class Level Lock | Code Factory”

Leave a comment