Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety between subsequent calls of an Executors.newSingleThreadExecutor

I have a question regarding using a single threaded executor. Since it reuses the same thread, does that means that If I modify an object state in one submit call, can I assume that another modification of that object state in subsequent calls of submit are thread safe? Let me give a toy example...

public class Main {

    public static void main(String[] args) throws Exception {

        final A a = new Main().new A();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<Integer> callable = new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return a.modifyState();
            }
        };

        /* first call */
        Future<Integer> result = executor.submit(callable);
        result.get();

        /* second call */
        result = executor.submit(callable);
        int fin = result.get();
        System.out.println(fin);

        executor.shutdown();
    }

    class A {

        private int state;

        public int modifyState() {
            return ++state;
        }

        public int getState() {
            return state;
        }

    }
}

So I am sharing object A. I submit a callable and modify it's state first ( see /* first call / ). I then do another submit call, modify again A state. (/ second call */).Now my big question

Is it safe to say that, since it's the same thread, the second submit call will see A.state as being 1? Or could it see it as being 0 in some cases too?

So basically I am asking if it's safe to modify variables that are not marked as volatile/accessed from synchronized blocks in subsequent submit calls of a single thread executor?, since it reuses the same thread

What exactly does thread reusing means regarding executors? Is it really the same thread at OS level in the case of an single thread executor?

like image 372
adragomir Avatar asked Feb 23 '14 20:02

adragomir


1 Answers

It actually doesn't matter that it is single threaded. The javadoc of ExecutorService states:

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

like image 52
assylias Avatar answered Sep 27 '22 21:09

assylias