gpt4 book ai didi

java - 线程获取已被其他线程获取的 ReentrantLock

转载 作者:行者123 更新时间:2023-11-30 08:11:35 27 4
gpt4 key购买 nike

我们的应用程序在 WebLogic 12c 中运行,正在从队列系统中检索消息,我们从中检索消息的队列配置为 FIFO。我们使用 Spring 来配置检索功能,并且容器 (org.springframework.jms.listener.DefaultMessageListenerContainer) 和消息监听器 (org.springframework.jms.core.support.JmsGatewaySupport) 都是单例。此外,该容器默认配置了一个 WorkManager 作为任务执行器。为了保证消息以预期的顺序(它们发送到队列的顺序)进行处理,我们在监听器中使用了 ReentrantLock,并且我们期望消息被一条一条地检索和处理。监听代码如下:

public class JmsReceiveAdapterImpl extends JmsGatewaySupport implements SessionAwareMessageListener {
private final ReentrantLock lock = new ReentrantLock(true);
[...]
public void onMessage(Message rcvMessage, Session session) throws JMSException {
lock.lock();
logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId());
try {
[...]
} finally {
logger.warn("Lock is going to be released by thread: " + Thread.currentThread().getId());
lock.unlock();
}
}
}

即使两条消息以正确的顺序放置在队列中,并且按照该顺序使用(回想一下队列是一个 FIFO 队列),但应用程序以某种方式并行处理这两条消息,如图所示在以下日志 block 中:

    Lock has been acquired by thread: 28    Backout count: 1    Message 1 / 1 received from XXX Message ID1 received.    Lock has been acquired by thread: 54     Backout count: 1    Message 1 / 1 received from XXX Message ID2 received.    ***** ERROR *****    Lock is going to be released by thread: 54    Lock is going to be released by thread: 28

我们为什么会出现这种行为?有什么想法吗?

非常感谢您。

最佳答案

改变

logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId());

logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId() + " And Object " + System.identityHashCode(this));

您可能会看到 System.identityHashCode 将是两个不同的数字。如果它是同一个对象,则 identityHashCode 将是相同的。如果它们不同,则意味着它们是不同的对象。

这告诉你的是,有多个 ReentrantLock 实例,并且不支持对不同实例的互斥。

关于java - 线程获取已被其他线程获取的 ReentrantLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30920167/

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