Executor.execute() JMM保证
考虑以下代码片段:
public class A {
private final Executor executor = Executors.newCachedThreadPool();
private final Queue<Object> messageQueue = new ConcurrentLinkedQueue<M>();
public void sendMessage(Object message) {
messageQueue.offer(message);
executor.execute(new Runnable() {
@Override
public void run() {
final Object message = messageQueue.poll();
// Can message == null?
}
});
}
}
当 Runnable 实例尝试检索消息时,是否可以保证 messageQueue 包含该消息?或者更笼统地说:JIT/JVM 可以根据 JMM 对两个函数调用重新排序吗?
Consider the following code snipet:
public class A {
private final Executor executor = Executors.newCachedThreadPool();
private final Queue<Object> messageQueue = new ConcurrentLinkedQueue<M>();
public void sendMessage(Object message) {
messageQueue.offer(message);
executor.execute(new Runnable() {
@Override
public void run() {
final Object message = messageQueue.poll();
// Can message == null?
}
});
}
}
Is it guaranteed that messageQueue contains the message by the time when the Runnable instance will try to retrieve it? Or to phraise it a little bit more general: can two function calls be reordered by JIT/JVM according to JMM?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果没有其他生产者/消费者。
Executor.execute()
建立一个happens-before关系。因此,offer() 中的所有内容都发生在 poll() 之前。poll()
可以看到offer()
的效果。尽管没有正式指定,但根据任何常识,poll()
应该返回刚刚添加到队列中的对象。Yes, if there are not other producers/consumers.
Executor.execute()
establish a happens-before relationship. Therefore everything inoffer()
happens-beforepoll()
.poll()
sees the effect ofoffer()
. Although not formally specified, by any common sense,poll()
should then return the object just added to the queue.