Skip to content

Instantly share code, notes, and snippets.

@RomanIakovlev
Created January 21, 2014 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RomanIakovlev/8540439 to your computer and use it in GitHub Desktop.
Save RomanIakovlev/8540439 to your computer and use it in GitHub Desktop.
On Android, this can be used to schedule callbacks back on the caller thread, if it has a Looper installed, or to the UI thread otherwise.
package com.example.concurrent;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
/**
* When the calling thread has a Looper installed (like the UI thread), an instance of ExecuteOnCaller will submit
* Runnables into the caller thread. Otherwise it will submit the Runnables to the UI thread.
*/
public class ExecuteOnCaller implements Executor {
private static ThreadLocal<Handler> threadLocalHandler = new ThreadLocal<Handler>() {
@Override
protected Handler initialValue() {
Looper looper = Looper.myLooper();
if (looper == null)
looper = Looper.getMainLooper();
return new Handler(looper);
}
};
private final Handler handler = threadLocalHandler.get();
@Override
public void execute(Runnable command) {
handler.post(command);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment