Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

Proper Synchronization in Java

Posted on Aug. 3, 2018
In this article I will explain how to properly use synchronization in Java. Many developers think that synchronization is for mutual exclusion. But there is more to it. You can end up with hard to detect bug if synchronization is not properly used.

In this article I will explain how to properly use synchronization in Java. Many developers think that synchronization is for mutual exclusion. But there is more to it. You can end up with hard to detect bug if synchronization is not properly used.


Without wasting any time let's look at the below code.


public class MainThread{
private static boolean stopExecution;

private static void main(String [] args) throws InterruptedException{
Runnable runnable = new Runnable() {
@Override
public void run() {
while(!stopExecution){
//Do something
}
}
};

Thread otherThread = new Thread(runnable);
otherThread.start();

Thread.sleep(1000);
stopExecution = true;
}
}

How long do you expect the other thread to run? The logic is simple right. We have created one more thread from the main thread. This other thread is checking the status of the variable stopExecution in a while loop which is initially set to false by default.

The main thread then sleeps for a minute allowing the other thread to run (in case it has not got the chance to run yet). After one minute of sleeping it sets the stopExecution to true.

This makes the condition inside the while loop of the other thread to FALSE and the other thread also stops. This is the simple logic that should work.

But not really.

In absence of synchronization the while loop inside the other thread may get translated as below.

if(!stopExecution){
while(true){
//Do something
}
}

So, in reality the other thread may continue forever.

We can prevent this by using synchronization as below.

public class MainThread{
private static boolean stopExecution;

private static synchronized void setStopExecution(){
stopExecution = true;
}

private static synchronized boolean isStopExecution(){
return stopExecution;
}

private static void main(String [] args) throws InterruptedException{
Runnable runnable = new Runnable() {
@Override
public void run() {
while(!isStopExecution()){
//Do something
}
}
};

Thread otherThread = new Thread(runnable);
otherThread.start();

Thread.sleep(1000);
setStopExecution();
}
}

And Yes. Both setStopExecution() and isStopExecution() need to be synchronized. It's not sufficient to synchronize only the setStopExecution() method. In fact synchronization does not have any meaning if both the methods are not synchronized.


Here Synchronization is solely used for communication between the threads. In our example above we can get rid of the synchronization by declaring the variable stopExecution volatile. By declaring volatile, we can force the threads to always get the latest copy of the variable.


So, if the variable is updated by a thread, all the other threads accessing that variable will always get the latest copy.

Here is the code using volatile.

public class MainThread{

private static volatile boolean stopExecution;

private static void main(String [] args) throws InterruptedException{
Runnable runnable = new Runnable() {
@Override
public void run() {
while(!stopExecution){
//Do something
}
}
};

Thread otherThread = new Thread(runnable);
otherThread.start();

Thread.sleep(1000);
stopExecution = true;
}
}


However you need to be very careful while using volatile. Always perform atomic operation on your volatile variable.

Suppose you are using an operation on your volatile variable which is not atomic but your application requires it to be atomic then go for Synchronization.

Sharing is Caring!

Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

GET FREE UPDATES


RECOMMENDED POSTS FOR YOU


profile image

Kaushik Baruah


ABOUT

My name is Kaushik Baruah and I am the chief blogger on this Blog. I have developed this Blog from scratch using Django as the backend and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects. You can follow me on Twitter, Facebook and Google+

GET FREE UPDATES

POPULAR POSTS

Copyright © 2018
About Us

My name is Kaushik Baruah and I am the chief blogger on this Blog. I have developed this Blog from scratch using Django as the backend and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects.

Get Free Updates