Question

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?

Was it helpful?

Solution 2

Executors.newSingleThreadExecutor() gives you thread safety by guaranteeing only one thread running at a time. It also gives you grantee about visibility which means any state change during one thread execution will be visible to next thread execution.

OTHER TIPS

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top