Skip to content

Instantly share code, notes, and snippets.

@javieritis
Last active December 16, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javieritis/c9b4f2bef35aed78ffeb29d69fc0b27b to your computer and use it in GitHub Desktop.
Save javieritis/c9b4f2bef35aed78ffeb29d69fc0b27b to your computer and use it in GitHub Desktop.
new MyCustomAsyncTask().executeOnExecutor(ExecutorManager.getInstance().getExecutor())
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ExecutorManager {
private static volatile ExecutorManager sSoleInstance;
private ExecutorService executor;
private ThreadPoolExecutor threadPoolExecutor;
public static ExecutorManager getInstance() {
if (sSoleInstance == null) {
synchronized (ExecutorManager.class) {
if (sSoleInstance == null) {
sSoleInstance = new ExecutorManager();
}
}
}
return sSoleInstance;
}
private ExecutorManager() {
if (sSoleInstance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public ExecutorService getExecutor() {
if (executor == null) {
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
int KEEP_ALIVE_TIME = 1;
TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.MINUTES;
int maxWorkCount = 1_000;
// int coreAmount = 8;
// int overrun = 4;
// executor = new ThreadPoolExecutor(coreAmount, coreAmount + overrun, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(maxWorkCount));
threadPoolExecutor = new ThreadPoolExecutor(NUMBER_OF_CORES * 5,
NUMBER_OF_CORES * 5,
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
new ArrayBlockingQueue<Runnable>(maxWorkCount));
executor = threadPoolExecutor;
}
return executor;
}
public int getActiveThreadCount() {
if (threadPoolExecutor != null) {
return threadPoolExecutor.getActiveCount();
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment