Synchronization

Threading is a very powerful technique which is sometimes very hard to control, especially when it is accessing shared resources.

In such cases, the threads have to be coordinated, otherwise it will violate , data of the whole application.

For example, a printer can’t be used to print two documents at the same time and if there are multiple printing requests, threads managing these printing operations needs to be coordinated.

Other example would be simultaneously operating the same bank account: it is not correct to do both deposit and withdraw operations on a bank account at the same time.

Multi-threading may lead to various type of concurrency issues when not controlled, The concurrency issues can be like that:

  • Race condition
  • Deadlock
  • Lock starvation

Race Condition :

A race condition is that situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled.

Race conditions can be lead to un-predictable results and subtle program bugs. A race condition can resolved by using Synchronization in the code

Deadlock :

Deadlock can be occur in a situation when a thread is waiting for an object lock, that is a acquired by another thread and second thread is waiting for an object lock and that is acquired by first thread.

Since, the both threads are waiting for each other to release the lock, this condition is called deadlock.

Lock Starvation :

A thread with the lowest priority might not ever get access to the shared resources as long as the threads with higher priority exists. That situation for the thread is known as lock starvation.

Overcome concurrency Issues

To overcome these concurrency issues while implementing multi-threading java provides and the concept of synchronization.

Synchronization is capability to control the access of multiple threads to any shared resource.

Synchronization is better when we want only one thread can access the shared resource at a time.

Java also provides a synchronized keyword which is used to create a synchronized block or method. Once a block or method is synchronized the they cannot be accessed by multiple threads at a time.

This helps is reducing the concurrency issues.

  • If we declare any method as synchronized, then it is known as synchronized method.
  • Synchronized method is used to lock an object for any shared resource.
  • When a thread called a synchronized method, it automatically acquires the lock for that object and releases it when the method returns.

Now we understand synchronization with the help of an example for printing table of 2 numbers concurrently

Example without using a synchronization


class Table {
 void printTable(int num) {
  //method not synchronized        
  for (int i = 1; i & lt = 5; i++) {
   System.out.println(num * 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 create one object  
  MyThread1 tobj1 = new MyThread1(obj);
  MyThread2 tobj2 = new MyThread2(obj);
  tobj1.start();
  tobj2.start();
 }
}


Output: 
5 
100 
10 
200 
15 
300 
20 
400
25 
500 

Example using synchronization


class Table {
 synchronized void printTable(int num) {
  //method is synchronized        
  for (int i = 1; i <= 5; i++) {
   System.out.println(num * 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 create  one object   
  MyThread1 tobj1 = new MyThread1(obj);
  MyThread2 tobj2 = new MyThread2(obj);
  t1.start();
  t2.start();
 }
}
//-------
Output:
 5
10
15
20
25
100
200
300
400
500

cccccc

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group