What is Synchronization in Java

Posted By : Mohit Kumar | 28-Feb-2019

Synchronization

At times once quite one thread tries and access a shared resource, we want to confirm that resources are utilized by only 1 thread at a time. the method by that this can be achieved is named synchronization. The synchronization keyword in java creates a block of code cited as crucial section.

Syntax:

synchronized (object)
{
//statement to be synchronized
}

 

Why we use Synchronization

 

If we tend to don't use synchronization and let 2 or a lot of threads access a shared resource at an identical time, it'll result in distorted results.

Consider Associate in Nursing example, Suppose we've 2 totally different threads T1 and T2, T1 starts execution and save bound values in an exceedingly file temporary.txt which can be wont to calculate some result once T1 returns. Meanwhile, T2 starts and before T1 returns, T2 amendment the values saved by T1 within the file temporary.txt (temporary.txt is that the shared resource). currently, clearly, T1 can come back the wrong result.

To prevent such issues, synchronization was introduced. With synchronization in higher than case, once T1 starts victimization temporary.txt file, this file is going to be locked(LOCK mode), and no different thread is going to be able to access or modify it till T1 returns.

 

 

Using Synchronized Methods
 
Using synchronic ways may be thanks to accomplishing synchronization. however, lets 1st see what happens after we don't use synchronization in our program.

 Example with no Synchronization

class First
{
 public void display(String msg)
 {
  System.out.print ("["+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println ("]");
 }
}

class Second extends Thread
{
 String msg;
 First fobj;
 Second (First fp,String str)
 {
  fobj = fp;
  msg = str;
  start();
 }
 public void run()
 {
  fobj.display(msg);
 }
}

public class Syncro
{
 public static void main (String[] args)
 {
  First fnew = new First();
  Second ss = new Second(fnew, "welcome");
  Second ss1= new Second (fnew,"new");
  Second ss2 = new Second(fnew, "programmer");
 }
}


Output:-

 

[welcome [ new [ programmer]
]
]

 

In the higher than program, object view of sophistication 1st is shared by all the 3 running threads(ss, ss1, and ss2) to decision the shared method(void display). therefore the result's unsynchronised and such scenario is termed Race condition.


Synchronized Keyword
To synchronize higher than program, we have a tendency to should synchronize access to the shared display() technique, creating it offered to just one thread at a time. this can be done by exploitation keyword synchronal with display() technique.


synchronized void display (String msg)


Using Synchronized block

If you have to synchronize access to an object of a class or you only want a part of a method to be synchronized to an object then you can use synchronized block for it.

 

class First
{
 public void display(String msg)
 {
  System.out.print ("["+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println ("]");
 }
}

class Second extends Thread
{
 String msg;
 First fobj;
 Second (First fp,String str)
 {
  fobj = fp;
  msg = str;
  start();
 }
 public void run()
 {
  synchronized(fobj)       //Synchronized block
  {
   fobj.display(msg);
  }
 }
}

public class Syncro
{
 public static void main (String[] args)
 {
  First fnew = new First();
  Second ss = new Second(fnew, "welcome");
  Second ss1= new Second (fnew,"new");
  Second ss2 = new Second(fnew, "programmer");
 }
}

 


Output:-

 

[welcome]
[new]
[programmer]

 

Because of the synchronized block, this program gives the expected result.

 

About Author

Author Image
Mohit Kumar

Mohit has a good knowledge in core Java and Adv Java. He is comfortable with Html and css. His hobbies are to watch movies,listing to music, playing video games.

Request for Proposal

Name is required

Comment is required

Sending message..