我有这个方法
@RequestMapping(value = "/affaires",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Affaire> createAffaire(@RequestBody Affaire affaire, HttpServletRequest request) throws URISyntaxException {
Long idMax = affaireRepository.getMaxId();
affaire.setReferenceAffaire("AF_"+LocalDate.now().getYear()+" - "+idMax);
Affaire result = affaireRepository.save(affaire);
我的问题:在我的数据库中,我有 2 个具有相同 ReferenceAffaire 的事务。
所以我猜测该方法在同一时间被调用两次,并且每次 idMax 都是相同的。
有没有办法避免这个方法在同一时间被多次调用?
最佳答案
在函数声明中添加synchronized
。这完全阻止了您想要的事情:想要同时调用此函数的线程被放入队列中并一个接一个地执行
public synchronized ResponseEntity<Affaire> createAffaire(@RequestBody Affaire affaire, HttpServletRequest request) throws URISyntaxException {
参见 documentation在这里。
关于java - 同时多次调用方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53750878/