gpt4 book ai didi

java - 在实例对象上同步

转载 作者:行者123 更新时间:2023-12-01 17:08:04 25 4
gpt4 key购买 nike

我有一个服务方法,基本上是将一条记录插入数据库。我想要实现的是基于对象或其变量来阻止一段代码。

我需要根据此 id 阻止其他线程:rcvTransactionRequest.getPoDistributionId()我不想阻止进入此方法的所有线程。最后,我试图验证不应超过的应收数量,如果多个线程进入临界区,则可能会发生这种情况。

    PoDistPayload poDistPayload = poDistService.getPoDist(rcvTransactionRequest.getPoDistributionId());
synchronized (poDistPayload) {
if (!poDistService.isReceivable(poDistPayload, rcvTransactionRequest.getQuantity()))
throw ebsExceptionFactory.build(1036L, rcvTransactionRequest.getQuantity(), poDistPayload.getReceivableQuantity());

PoDistRcv poDistRcv = PoDistRcv.of(rcvTransactionRequest);
poDistRcv.setStatus(Status.TRANSACTION_STARTED);
poDistRcv = poDistRcvRepository.save(poDistRcv);
return new BaseTransactionResponse(poDistRcv.getTransactionId(), serialCountPerRequest, poDistRcv.getStatus());
}

最佳答案

您可以使用 ConcurrentMap 来实现简单的锁定方案:

Object newLock=new Object();
Object existingLock;
// Wait until this thread can acquire lock
synchronized(newLock) {
do {
existingLock=cMap.putIfAbsent(distributionId,newLock);
if(existingLock!=null) {
// Locked by another thread. You can fail immediately, or wait until the lock is released
synchronized(existingLock) {
// Need timeout here because lock holder may notify before we wait
existingLock.wait(timeout);
}
}
} while(existingLock!=null);
// You have the lock
// Do work
// Unlock and notify
cMap.remove(distributionId,newLock);
newLock.notify();
}

关于java - 在实例对象上同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61446624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com