Sunday, March 10, 2019

Race condition in multi-threaded application

When we develop the multi-threaded application, it's critical to ensure that no race condition occurs. Otherwise, our program will produce the inconsistent result.
Let see the demo program. When we execute this program for 5 times, it will output 1000 for each run.
public class RaceCondition implements Runnable {
static Object lock = new Object();
static int sharedNumber = 0;

public static void main(String[] args) {
Thread t1 = new Thread(new RaceCondition());
Thread t2 = new Thread(new RaceCondition());
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sharedNumber);
}

public void run() {
boolean wait = true;
for (int i = 0; i < 500; i++) {
synchronized (lock) {
int buffer = sharedNumber;
buffer++;
if (Math.random() > 0.5 && wait) {
wait = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sharedNumber = buffer;
}
}
}
}
Ok, let's comment "synchronized" code line and it's closing curly brace line. This time, we will have 5 different values after executing for 5 times.
synchronized block ensure that only one thread can execute on the share/same object at a time in its block. It prevent the possible race condition.

No comments:

Post a Comment

Image compression using C#

Sometimes, we need to compress the image files while maintaining the image quality. This can be achieved by the following C# implementation....