×

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

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

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 Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.