Race condition for member field occurs when we declare an instance variable in a servlet class and use the same in any of the method inside the same class.
public class Test {
private boolean isRaceCondition;
private String myRaceCondition;
public void testMyMethod(){
If(isRaceCondition){
myRaceCondition= “Yes It is”;
}
else{
myRaceCondition= “No It is not”;
}
}
}
The above code will run correctly in single threaded environment but in multithreaded environment, it is possible that more than one thread is working on the same piece of code and can cause data integrity issue.
For example Thread T1 set the value of isRaceCondition= true but before T1 can execute the method testMyMethod(), another thread T2 reset the value of isRaceCondition= false so now when T1 try to execute the testMyMethod() it will see isRaceCondition to false and It will set myRaceCondition= “No It is not”;
To resolve this issue, the simplest solution is
1. In case we can set initial value to variable and essentially they are constant.
private static final boolean isRaceCondition=True;
private static final String myRaceCondition=” Yes It is” ;
2. In case we CANNOT set initial value, we use volatile. This will ensure that value of variable is always fetched from memory before they are used
private static volatile boolean isRaceCondition;
private static volatile String myRaceCondition;
public class Test {
private boolean isRaceCondition;
private String myRaceCondition;
public void testMyMethod(){
If(isRaceCondition){
myRaceCondition= “Yes It is”;
}
else{
myRaceCondition= “No It is not”;
}
}
}
The above code will run correctly in single threaded environment but in multithreaded environment, it is possible that more than one thread is working on the same piece of code and can cause data integrity issue.
For example Thread T1 set the value of isRaceCondition= true but before T1 can execute the method testMyMethod(), another thread T2 reset the value of isRaceCondition= false so now when T1 try to execute the testMyMethod() it will see isRaceCondition to false and It will set myRaceCondition= “No It is not”;
To resolve this issue, the simplest solution is
1. In case we can set initial value to variable and essentially they are constant.
private static final boolean isRaceCondition=True;
private static final String myRaceCondition=” Yes It is” ;
2. In case we CANNOT set initial value, we use volatile. This will ensure that value of variable is always fetched from memory before they are used
private static volatile boolean isRaceCondition;
private static volatile String myRaceCondition;