0

I have Spring Controller for saving data to database, and this method generating receiptNo (the receiptNo value is generated using some database field value) for example: xxx/ddMMyy/compId.

where xxx is select max(substr("receiptNo")) from table, and compId is from the session. After receiptNo is generated, then the value will be saved to another table.

my Controller is:

@Controller
public class foo{

private Object LOCK_OBJECT = new Object();

@RequestMapping(value = "/generateAndSave", method = RequestMethod.POST)
    public ModelAndView generateAndSave(@ModelAttribute("tform") TempForm tform, HttpServletRequest request) {

        // Some Logic
        synchronized (LOCK_OBJECT) {
           String max = doGetMax(tform);
           SomePojo domain = doGenerate(max, compId);
           doStore(domain);
        }
        modelAndView.addObject("key", "value");
        return modelAndView;
    }
}

My Question is, Should i use synchronized (LOCK_OBJECT) { } block for ensuring unique receiptNo?

My concern is on xxx value, if i not use synchronized (LOCK_OBJECT) { } block, some user will get same xxx value.

Please Advise,

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
dibrut
  • 81
  • 1
  • 2
  • 9
  • [this](http://stackoverflow.com/questions/19168150/private-method-inside-spring-mvc-controller-is-thread-safe?rq=1) and [this](http://stackoverflow.com/questions/14145761/are-spring-controllers-thread-safe) might help. – Sabir Khan Feb 18 '16 at 05:20
  • also elaborate if `doGetMax` and `doStore' are `private methods` of controller or methods of some service object. – Sabir Khan Feb 18 '16 at 05:29
  • 1
    yes, you should use `synchronized`. Spring does not care about synchronization, you should do it by yourself, otherwise different threads will be able to get same max value from database. – Ken Bekov Feb 18 '16 at 08:03

0 Answers0