Executor.execute()JMM保证 [英] Executor.execute() JMM guarantee
问题描述
请考虑以下代码snipet:
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?
}
});
}
}
是否保证messageQueue包含消息的时间当Runnable实例会尝试检索它吗?或者phraise它有点更一般:可以两个函数调用由JIT / JVM根据JMM重新排序?
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?
推荐答案
是,如果没有其他生产者/消费者。
Yes, if there are not other producers/consumers.
Executor.execute()
建立发生先于关系。因此, offer()
发生之前 poll()
poll()
看到 offer()
的效果。虽然没有正式指定,但是通过任何常识, poll()
应该返回刚刚添加到队列中的对象。
Executor.execute()
establish a happens-before relationship. Therefore everything in offer()
happens-before poll()
. poll()
sees the effect of offer()
. Although not formally specified, by any common sense, poll()
should then return the object just added to the queue.
这篇关于Executor.execute()JMM保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!