Search code examples
javaspringspring-mvcfortify

How to fix Fortify Race Condition: Singleton Member Field issue


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

Solution

  • Try do redesign your controller to not put state in it. Alternatively you can think about using AtomicInteger

    AtomicInteger seq = new AtomicInteger();//Global variable
    
    @RequestMapping(value = "/agn/AP1W01A_004", method=RequestMethod.GET)
        public ModelAndView welcomeGrid(@RequestParam("payType")String payType){
            seq.set(gnRecService.findTheLastPK(payType));
            ModelAndView view = new ModelAndView(".agn.AP1W01A_004");
            return view;
        }
    
        public ModelAndView showPk() {
            final int localSeq = seq.addAndGet(2); 
            ModelAndView view = new ModelAndView(".agn.AP1W01A_004");
            view.addObject("seq",localSeq)
            return view;
        }