in the spring container environment, does it ensure that the program is available by performing time-consuming logic through synchronized (this) locks?
I tested that if there is no return value, the order can be guaranteed, and if there is a return value, there will be a problem.
: the reason for adding synchronized is that it may concurrently access lockUserVouchers to modify the data state, and the status will be returned if the modification succeeds or fails
@Test
public void testLock() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 1; i <= 3; iPP) {
new Thread(new RunnerLock(userVouchersService, latch)).start();
}
latch.await();
}
public class RunnerLock implements Runnable {
UserVouchersService userVouchersService;
CountDownLatch countDownLatch;
public RunnerLock(UserVouchersService userVouchersService, CountDownLatch countDownLatch) {
this.userVouchersService = userVouchersService;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
CsAuctionUserVouchers csAuctionUserVouchers = new CsAuctionUserVouchers();
csAuctionUserVouchers.setId(ThreadLocalRandom.current().nextLong(0, 9999));
long l = userVouchersService.lockUserVouchers(csAuctionUserVouchers);
log.info("--------------- --- {}---------------------------------", l);
countDownLatch.countDown();
}
}
@Transactional(rollbackFor = Exception.class)
public long lockUserVouchers(CsAuctionUserVouchers csAuctionUserVouchers) {
synchronized (this) {
log.info("-------------------test----------------------");
try {
Thread.sleep(1000);
//
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("------------------ --test----------------------");
return csAuctionUserVouchers.getId();
}
}