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());
try {
} catch (Exception e) {

public void run() {
boolean wait = true;
for (int i = 0; i < 500; i++) {
synchronized (lock) {
int buffer = sharedNumber;
if (Math.random() > 0.5 && wait) {
wait = false;
try {
} catch (InterruptedException e) {
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....