Thursday, 7 September 2017

Revision Day 7: Multi-threading- synchronized : Class level vs object level

Class level vs object level

Class Level:-

private void lock() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
synchronized (Foo.class) {
System.out.println("in Class  " + Thread.currentThread().getName());
Thread.sleep(4000);
System.out.println("in Class " + Thread.currentThread().getName() + " end");
}

}
main(){
Foo b1 = new Foo();
Thread t1 = new Thread(b1);
Foo b2 = new Foo();
Thread t3 = new Thread(b2);
t1.setName("t1");
t3.setName("t3");
t1.start();
t3.start();
}

Output:-
t1
t3
in Class  t1
in Class t1 end2
in Class  t3
in Class t3 end2

in case of Class level blocking,only one thread can run the class-synchronized method at a time,Also to note an instance synchronized method can also run simultaneously

As seen above eventhough t1 and t3 entered the block at the same time,only after completion of t1, t3 can start accessing the method.

Object Level:-

public void Lock() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
synchronized (this) {
System.out.println("in obj " + Thread.currentThread().getName());
Thread.sleep(4000);
System.out.println("in obj " + Thread.currentThread().getName() + " end");
}
}

main(){
Foo b1 = new Foo();
Thread t1 = new Thread(b1);
Foo b2 = new Foo();
Thread t3 = new Thread(b2);
t1.setName("t1");
t3.setName("t3");
t1.start();
t3.start();
}

Output:-
t1
t3
in obj t1
in obj t3
in obj t3 end
in obj t1 end

In case of instance synchronized method,both t1 and t3 can start accessing the method at the same time because both are acting on 2 different objects.

No comments:

Post a Comment

Installing Docker and Minikube

  install docker-   sudo apt install docker.io   set user to docker group:- sudo gpasswd -a   {user} docker   imp commands:- ...