问题
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?
回答1:
Yes, if there are not other producers/consumers.
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.
来源:https://stackoverflow.com/questions/8147015/executor-execute-jmm-guarantee