How to fix Fortify Race Condition: Singleton Member Field issue

Hamilton Lin picture Hamilton Lin · Aug 4, 2016 · Viewed 14k times · Source

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

Answer

Manas picture Manas · Dec 25, 2018

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;