NamHo Lee NamHo Lee - 1 year ago 67
Android Question

in java do thread local cached memory get flushed to main memory when destroyed ???

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){ = sv;

public void run(){

// Main Thread

ExecutorService ex = Executors.newSingleThreadExecutor();

StateSaver sv = new StateSaver();

public void functionCalledByMainThread(){

ex.submit(new rnbl(sv));


However the problem is that I found out when the newSingleThreadExecutor is left idle for long, it might just destroy the thread made by it and replace it with a new one when needed.

So what I am worried is that, what if situations like below occur? :

  1. the worker thread updated the state variable

  2. the variable is updated in the threads cached memory but not applied to the main memory yet ( the variable should NOT be volatile )

  3. the worker thread gets destroyed

  4. the update is never applied to the main memory ...

Then if the executor creates a new thread to go on with the task, the saved state might be incorrect right? Of course using volatile this should be easy but I need to not use volatile

Or is it guaranteed that when a thread is destroyed, all of it's changes made to variables are flushed to the main memory?

Answer Source

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());
 // do stuff
 // 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 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().

Therefore, the way to get the consistency you want is to call get() on the Future for the task.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download