I encounter a problem. we use Spring MVC framework in my Project,but Spring MVC default Controller is Singleton Model. I change Controller use @Scope("session") by session to avoid race Condition problem(everyone has own Controller).
@Controller
@Scope("session")
public class AP0Controller extends BaseController {
@Autowired
GnRecService gnRecService;
Integer seq = null;//Global variable
@RequestMapping(value = "/agn/AP1W01A_004", method=RequestMethod.GET)
public ModelAndView welcomeGrid(@RequestParam("payType")String payType){
seq = gnRecService.findTheLastPK(payType);
ModelAndView view = new ModelAndView(".agn.AP1W01A_004");
return view;
}
public ModelAndView showPk() {
seq +=2;
ModelAndView view = new ModelAndView(".agn.AP1W01A_004");
view.addObject("seq",seq)
return view;
}
}
After Scanned By HP Fortify,the report indicated this will cause Race Condition. How can I fix it and pass the issue?
seq +=2;//Race Condition: Singleton Member Field
Race condition occurs when we declare an instance variable in a 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 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" ;
Otherwise 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;
For String and other object race condition we should we AtomicReference race condition.for example private AtomicReference name and generate setters and getters and simillarly for user defined objects AtomicReference person and generate setters and getters for this your race condition is solved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With