If callbacks aren't placed on an event queue, multiple threads begin to share access to someObj.
Object someObj = ...;
Runnable callback = new Runnable(){ someObj.doSomething(); };
executor.submit(new Runnable() {
public void run() {
... do something ...
// the callback is now run in a different thread
// than the thread that generated the task!
// Two different threads now access someObj.
callback.run();
}
});
someObj.doSomething();
Make a simple event queue & task dispatcher class. All callbacks are given to the TaskDispatcher to run. This confines callbacks to a specific thread. Just like what we do in Swing.
TaskDispatcher
// on some custom event dispatch thread
while (true) {
Task t = queue.take();
t.run();
}
Object someObj = ...;
Runnable callback = new Runnable() { someObj.doSomething(); };
// submitting a task to run in the background
executor.submit(new Runnable() {
... do some intense work ...
// run the callback back on the dispatch thread
// only 1 thread ever accesses someObj.
TaskDispatcher.invokeLater(callback);
});
someObj.doSomething();