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?
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.