I am trying to design an android app that uses a worker thread made by Executors.newSingleThreadExecutor()
However I just want that worker thread to handle the continuous tasks sent by the main thread while saving some information belonging to that worker thread. (the main thread doesn't need to know, just the worker thread should keep that information internally.
// State saver class , once made by main thread only accessed by worker thread
public class StateSaver{
public int count;
}
// Runnable obj that will be sent to worker thread from main thread
public class rnbl implements Runnable{
final public StateSaver sv;
public rnbl(StateSaver sv){
this.sv = sv;
}
@Override
public void run(){
sv.count++;
}
}
// Main Thread
ExecutorService ex = Executors.newSingleThreadExecutor();
StateSaver sv = new StateSaver();
public void functionCalledByMainThread(){
ex.submit(new rnbl(sv));
}
If you want to ensure that the changes made by a thread that then terminates are visible to another thread, then you can use Thread.join()
. That gives you a guaranteed happens-before relationship.
For example:
Thread t = new Thread(new SomeRunnable());
t.start();
// do stuff
t.join();
// After the 'join', all memory writes made by Thread t are
// guaranteed to be visible to the current thread.
But you are actually asking about an ExecutorService
where the thread won't be available for you to "join".
The following memory consistency guarantees apply for an ExecutorService
:
Actions in a thread prior to the submission of a
Runnable
orCallable
task to anExecutorService
happen-before any actions taken by that task, which in turn happen-before the result is retrieved viaFuture.get()
.
Therefore, the way to get the consistency you want is to call get()
on the Future
for the task.