Likes

Synchronization in Java

Synchronization in Java

Synchronization in java is the capability of control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.


Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.


Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Here, we will discuss only thread synchronization.


Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive
1.       Synchronized method.
2.       Synchronized block.
3.       Static synchronization.
Cooperation (Inter-thread communication in java)


Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization


Understanding the concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.


Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
Class Table{  
  
void printTable(int n){//method not synchronized  
   for(int i=1;i<=5;i++){  
     System.out.println(n*i);  
     try{  
      Thread.sleep(400);  
     }catch(Exception e){System.out.println(e);}  
   }  
  
 }  
}  
  
class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
  
class Use{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  
Output: 5
       100
       10
       200
       15
       300
       20
       400
       25
       500
      


Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
//example of java synchronized method  
Class Table{  
 synchronized void printTable(int n){//synchronized method  
   for(int i=1;i<=5;i++){  
     System.out.println(n*i);  
     try{  
      Thread.sleep(400);  
     }catch(Exception e){System.out.println(e);}  
   }  
  
 }  
}  
  
class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
  
class Use{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
      



Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {   
  //code block   
}  
Example of synchronized block
Let's see the simple example of synchronized block.
  
class Table{  
  
 void printTable(int n){  
   synchronized(this){//synchronized block  
     for(int i=1;i<=5;i++){  
      System.out.println(n*i);  
      try{  
       Thread.sleep(400);  
      }catch(Exception e){System.out.println(e);}  
     }  
   }  
 }//end of the method  
}  
  
class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
  
class Use{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
      


      
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
static synchronization
Problem without static synchronization
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform static synchronization.
class Table{  
  
 synchronized static void printTable(int n){  
   for(int i=1;i<=10;i++){  
     System.out.println(n*i);  
     try{  
       Thread.sleep(400);  
     }catch(Exception e){}  
   }  
 }  
}  
  
class MyThread1 extends Thread{  
public void run(){  
Table.printTable(1);  
}  
}  
  
class MyThread2 extends Thread{  
public void run(){  
Table.printTable(10);  
}  
}  
  
class MyThread3 extends Thread{  
public void run(){  
Table.printTable(100);  
}  
}  
  
  
  
  
class MyThread4 extends Thread{  
public void run(){  
Table.printTable(1000);  
}  
}  
  
class Use{  
public static void main(String t[]){  
MyThread1 t1=new MyThread1();  
MyThread2 t2=new MyThread2();  
MyThread3 t3=new MyThread3();  
MyThread4 t4=new MyThread4();  
t1.start();  
t2.start();  
t3.start();  
t4.start();  
}  
}  
Output: 1
       2
       3
       4
       5
       6
       7
       8
       9
       10
       10      
       20
       30
       40
       50
       60
       70
       80
       90
       100
       100
       200
       300
       400
       500
       600
       700
       800
       900
       1000
       1000
       2000
       3000
       4000
       5000
       6000
       7000
       8000
       9000
       10000
      


      


Synchronized block on a class lock:
The block synchronizes on the lock of the object denoted by the reference .class name .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration:
static void printTable(int n) {  
    synchronized (Table.class) {       // Synchronized block on class A  
        // ...  
    }  
}  

Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Deadlock in java
Example of Deadlock in java:
public class DeadlockExample {  
  public static void main(String[] args) {  
    final String resource1 = "ratan jaiswal";  
    final String resource2 = "vimal jaiswal";  
    // t1 tries to lock resource1 then resource2  
    Thread t1 = new Thread() {  
      public void run() {  
          synchronized (resource1) {  
           System.out.println("Thread 1: locked resource 1");  
  
           try { Thread.sleep(100);} catch (Exception e) {}  
  
           synchronized (resource2) {  
            System.out.println("Thread 1: locked resource 2");  
           }  
         }  
      }  
    };  
  
    // t2 tries to lock resource2 then resource1  
    Thread t2 = new Thread() {  
      public void run() {  
        synchronized (resource2) {  
          System.out.println("Thread 2: locked resource 2");  
  
          try { Thread.sleep(100);} catch (Exception e) {}  
  
          synchronized (resource1) {  
            System.out.println("Thread 2: locked resource 1");  
          }  
        }  
      }  
    };  
  
      
    t1.start();  
    t2.start();  
  }  
}  
          
Output: Thread 1: locked resource 1
        Thread 2: locked resource 2

Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:
wait()
notify()
notifyAll()


1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.
Method
Description
public final void wait()throws InterruptedException
waits until object is notified.
public final void wait(long timeout)throws InterruptedException
waits for the specified amount of time.


2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:
public final void notify()


3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()


Understanding the process of inter-thread communication
inter thread communication in java
The point to point explanation of the above diagram is as follows:
Threads enter to acquire lock.
Lock is acquired by on thread.
Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits.
If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
Now thread is available to acquire lock.
After completion of the task, thread releases the lock and exits the monitor state of the object.


Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.


Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait()
sleep()
wait() method releases the lock
sleep() method doesn't release the lock.
is the method of Object class
is the method of Thread class
is the non-static method
is the static method
is the non-static method
is the static method
should be notified by notify() or notifyAll() methods
after the specified amount of time, sleep is completed.


Example of inter thread communication in java
Let's see the simple example of inter thread communication.
class Customer{  
int amount=10000;  
  
synchronized void withdraw(int amount){  
System.out.println("going to withdraw...");  
  
if(this.amount<amount){  
System.out.println("Less balance; waiting for deposit...");  
try{wait();}catch(Exception e){}  
}  
this.amount-=amount;  
System.out.println("withdraw completed...");  
}  
  
synchronized void deposit(int amount){  
System.out.println("going to deposit...");  
this.amount+=amount;  
System.out.println("deposit completed... ");  
notify();  
}  
}  
  
class Test{  
public static void main(String args[]){  
final Customer c=new Customer();  
new Thread(){  
public void run(){c.withdraw(15000);}  
}.start();  
new Thread(){  
public void run(){c.deposit(10000);}  
}.start();  
  
}}  
Output: going to withdraw...
       Less balance; waiting for deposit...
       going to deposit...
       deposit completed...
       withdraw completed
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread class for thread interruption.


The 3 methods provided by the Thread class for interrupting a thread
public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()


Example of interrupting a thread that stops working
In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don't want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's first see the example where we are propagating the exception.
class A extends Thread{  
public void run(){  
try{  
Thread.sleep(1000);  
System.out.println("task");  
}catch(InterruptedException e){  
throw new RuntimeException("Thread interrupted..."+e);  
}  
  
}  
  
public static void main(String args[]){  
A t1=new A();  
t1.start();  
try{  
t1.interrupt();  
}catch(Exception e){System.out.println("Exception handled "+e);}  
  
}  
}  
Output:Exception in thread-0 
       java.lang.RuntimeException: Thread interrupted...
       java.lang.InterruptedException: sleep interrupted
       at A.run(A.java:7)


Example of interrupting a thread that doesn't stop working
In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping but will not stop working.
class A extends Thread{  
public void run(){  
try{  
Thread.sleep(1000);  
System.out.println("task");  
}catch(InterruptedException e){  
System.out.println("Exception handled "+e);  
}  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
A t1=new A();  
t1.start();  
  
t1.interrupt();  
  
}  
}  
Output:Exception handled 
       java.lang.InterruptedException: sleep interrupted
       thread is running...


Example of interrupting thread that behaves normally
If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.
class A extends Thread{  
  
public void run(){  
for(int i=1;i<=5;i++)  
System.out.println(i);  
}  
  
public static void main(String args[]){  
A t1=new A();  
t1.start();  
  
t1.interrupt();  
  
}  
}  
Output:1
       2
       3
       4
       5


What about isInterrupted and interrupted method?
The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.
class InterruptedDemo extends Thread{  
  
public void run(){  
for(int i=1;i<=2;i++){  
if(Thread.interrupted()){  
System.out.println("code for interrupted thread");  
}  
else{  
System.out.println("code for normal thread");  
}  
  
}//end of for loop  
}  
  
public static void main(String args[]){  
  
InterruptedDemo t1=new InterruptedDemo();  
InterruptedDemo t2=new InterruptedDemo();  
  
t1.start();  
t1.interrupt();  
  
t2.start();  
  
}  
}  
Output:Code for interrupted thread
       code for normal thread
       code for normal thread
       code for normal thread
      


No comments: