Executor.execute() JMM guarantee

白昼怎懂夜的黑 提交于 2019-12-12 02:09:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!