【Java】java 并发访问函数返回值问题?

在spring 容器环境下,通过synchronized(this)锁来执行耗时逻辑,这样能保证程序可用吗?
我测试下来如果没有返回值是能保证顺序, 有返回值就有问题.
:加synchronized 的原因是可能会并发去访问lockUserVouchers修改数据状态,修改成功或失败返回状态

【Java】java 并发访问函数返回值问题?

@Test

public void testLock() throws InterruptedException {

CountDownLatch latch = new CountDownLatch(3);

for (int i = 1; i <= 3; i++) {

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();

}

}

回答

哪里有问题?

以上是 【Java】java 并发访问函数返回值问题? 的全部内容, 来源链接: utcz.com/a/87997.html

回到顶部