gpt4 book ai didi

java - 使用 BlockingQueue 时是否需要额外的同步?

转载 作者:太空狗 更新时间:2023-10-29 22:50:17 25 4
gpt4 key购买 nike

我有一个简单的 bean @Entity Message.java,它有一些正常的属性。该对象的生命周期如下

Message 的实例化发生在 Thread A 上,然后将其放入 blockingQueue 中

池中的另一个线程获取该对象并对其执行一些操作并更改 Message 的状态,之后该对象再次进入 blockingQueue。重复此步骤,直到条件使其停止。每次读取/写入对象都可能来自不同的线程,但保证一次只有一个线程读取/写入它。

鉴于这种情况,我需要同步 getters/setters 吗?也许使属性不稳定?或者我可以不同步就离开吗?

谢谢,希望我能澄清我在这里的内容。

最佳答案

不,您不需要同步访问对象属性,甚至不需要对成员变量使用 volatile

线程在将对象放入 BlockingQueue 队列之前执行的所有操作“发生在”对象出队之前。这意味着第一个线程所做的任何更改对第二个线程都是可见的。这是并发集合的常见行为。请参阅 BlockingQueue class documentation 的最后一段:

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

只要第一个线程在排队对象后不做任何修改,它就是安全的。

关于java - 使用 BlockingQueue 时是否需要额外的同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3661282/

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