Question

Suppose I have a Runnable that does a simple file writing operation, and this Runnable is called with an executor.

With executor being a single thread Executor class..

public void doThis() {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            file.write(_data);
        }
    });
}

does the immediate contents of _data get saved the moment execute() is called? Which means that once the runnable has been submitted to the queue, I can go ahead and make changes to _data, and the changes will not be written to the file?

_data = something
doThis();
_data = something else

is there a chance that I will end up doing file.write(something else)?

Was it helpful?

Solution

no to your first and second questions, and yes to your third question ... if the single thread that the executor is running on is a separate thread from the calling thread, then this is not a thread-safe operation. unless .execute() executes on the same exact thread as the caller, you need to avoid making changes to _data until .write is done.

A common way of working around this is to simply make a copy of _data before passing it off to the executor.

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