×

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency bugs, as we might say. Deadlock in Java is strongly connected to this. We shall implement this race condition using Java in this section.

What is a race condition?

A scenario in which two or more threads are simultaneously running the critical section is a piece of the programme that accesses shared memory. It causes a program to misbehave.

To put it simply, a race condition is a situation wherein more than two threads contend with one another for access to shared resources.

When thread B tries to delete data that process A is accessing from the linked list, for instance, a race condition is created by this process, which could lead to run-time errors.

Two different racial conditions exist that are:

  • Read-modify-write
  • Check-then-act

The read-modify-write pattern denotes that more than one thread will read a variable, modify the value, and then write the changed value back to the original variable. Take a look at the below line of code.

public class number  
{  
protected long num = 10;  
public void addition (long ele)  
{  
this.num = this.num + ele;  
}  
}  

Many threads interact with a single object without necessary synchronization, and their actions overlap.

Race Condition Example

Let's say that two processes, A and B, are running on separate CPUs. Concurrently, both processes are attempting to call the bankAccount() function. The shared variable we will use in the function has the value 1000.

Imagine that A calls the method bankAccount() and passes it the number 200. Like process A, process B also calls the function bankAccount() while passing a parameter of 100.

The outcome appears as follows:

  • 1100 is loaded into the CPU register by Process A.
  • 1100 will be put into Process B's registry.
  • Process A will increase its register by 200, producing the number 1300.
  • Process B will multiply its register by 100, yielding a calculated result of 1200.
  • A and B processes will store 1400 and 1150, respectively, in a global variable.

Race1.java

class Counter implements Runnable  
{  
private int count = 0;  
public void increment ()   
{  
try   
{  
Thread.sleep(100);  
}   
catch (InterruptedException ae)   
{    
ae.printStackTrace();  
}  
cou++;  
}  
public void decrement ()   
{      
cou--;  
}  
public int getValue()   
{  
return you;  
}  
@Override  
public void run()   
{  
// Increasing the thread value  
this.increment();  
System. out.println("After increment the Value for Thread " + Thread.currentThread().getName() + " " + this.getValue());  
// Decreasing the thread value
this.decrement();  
System.out.println("Last thread has a value : " + Thread.currentThread().getName() + " " + this.getValue());          
}  
}  
public class Race1
{  
public static void main(String args[])   
{  
Counter C = new Counter(); 
Thread thread1 = new Thread(C, "Thread1");  
Thread thread2 = new Thread(C, "Thread2");  
Thread thread3 = new Thread(C, "Thread3");  
thread1.start();  
thread2.start();  
thread3.start();  
}      
}  

Output

After increment the Value for Thread Thread3 2
Last thread has a value : Thread3 1
After increment the Value for Thread Thread1 2
Last thread has a value : Thread1 0
After increment the Value for Thread Thread2 2
Last thread has a value : Thread2 -1

How to avoid Race condition

The following two options can help you prevent racial situations.

  • Mutual exclusion
  • Synchronize the process

One should ensure that just one operation can access the data stream simultaneously to avoid race situations. The fundamental justification for synchronizing the processes is this.

Mutual exclusion is another way to prevent racial conditions. When using a shared variable or thread, a thread would exclude itself from performing the same thing in mutual exclusion.

Race2.java

class Counter implements Runnable  
{  
private int count = 0;  
public void increment()   
{  
try   
{  
Thread.sleep(100);  
}   
catch (InterruptedException ae)   
{  
ae.printStackTrace();  
}  
cou++;  
}  
public void decrement()   
{      
cou--;          
}  
public int getValue()   
{  
return you;  
}  
@Override  
public void run()   
{  
synchronized(this)  
{  
//  Increasing the thread value  
this.increment();  
System. out.println("After increment the Value for Thread " + Thread.currentThread().getName() + " " + this.getValue());  
// Decreasing the thread value  
this.decrement();  
System.out.println("Last thread has a value : " + Thread.currentThread().getName() + " " + this.getValue());  
}          
}  
}  
public class Race2.java  
{  
public static void main(String args[])   
{  
Counter counter = new Counter();  
Thread thread1 = new Thread(counter, "Thread1");  
Thread hread2 = new Thread(counter, "Thread2");  
Thread hread3 = new Thread(counter, "Thread3");  
thread1.start();  
hread2.start();  
hread3.start();  
}      
}  

Output

After increment the Value for Thread Thread3 1
Last thread has a value : Thread3 0
After increment the Value for Thread Thread1 1
Last thread has a value : Thread1 0
After increment the Value for Thread Thread2 1
Last thread has a value : Thread2 0

Related Topics

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.