Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Created September 10, 2018 21:12
Show Gist options
  • Save OrenBochman/b7f3d1870f5fb05df5e830e43e4ccea8 to your computer and use it in GitHub Desktop.
Save OrenBochman/b7f3d1870f5fb05df5e830e43e4ccea8 to your computer and use it in GitHub Desktop.
ThreadPoolExecutor in Android

ThreadPoolExecutor

ThreadPoolExecutor executes parallelized tasks across multiple different threads of a thread pool. To execute work concurrently and retain control over how the work is executed, this is the tool for the job.

Using ThreadPoolExecutor

  1. constructing a new instance
  2. confgure the many arguments of the thread pool
  3. if initializing ThreadPoolExecutor in a service, ensure to create it within onStartCommand() not onCreate()
  4. execute runnables on the ThreadPoolExecutor.
  5. shut it down when you are done a. executor.shutdownNow() b. executor.shutdown()
// Determine the number of cores on the device
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// Construct thread pool passing in configuration options
// int minPoolSize, int maxPoolSize, long keepAliveTime, TimeUnit unit,
// BlockingQueue<Runnable> workQueue
ThreadPoolExecutor executor = new ThreadPoolExecutor(
NUMBER_OF_CORES*2,
NUMBER_OF_CORES*2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
// Executes a task on a thread in the thread pool
executor.execute(new Runnable() {
public void run() {
// Do some long running operation in background
// on a worker thread in the thread pool!
}
});
executor.shutdown();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment