Created
July 24, 2018 20:24
-
-
Save arttuladhar/1b6598029865e74f9dd5b4944354f7c8 to your computer and use it in GitHub Desktop.
Global executor pools for the whole application.
Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind webservice requests).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AppExecutors { | |
// For Singleton instantiation | |
private static final Object LOCK = new Object(); | |
private static AppExecutors sInstance; | |
private final Executor diskIO; | |
private final Executor mainThread; | |
private final Executor networkIO; | |
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) { | |
this.diskIO = diskIO; | |
this.networkIO = networkIO; | |
this.mainThread = mainThread; | |
} | |
public static AppExecutors getInstance() { | |
if (sInstance == null) { | |
synchronized (LOCK) { | |
sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), | |
Executors.newFixedThreadPool(3), | |
new MainThreadExecutor()); | |
} | |
} | |
return sInstance; | |
} | |
public Executor diskIO() { | |
return diskIO; | |
} | |
public Executor mainThread() { | |
return mainThread; | |
} | |
public Executor networkIO() { | |
return networkIO; | |
} | |
private static class MainThreadExecutor implements Executor { | |
private Handler mainThreadHandler = new Handler(Looper.getMainLooper()); | |
@Override | |
public void execute(@NonNull Runnable command) { | |
mainThreadHandler.post(command); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment