Skip to content

Instantly share code, notes, and snippets.

@iRYO400
Created November 9, 2019 15:07
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 iRYO400/82fbda2ddf52f440a066c27fbe12f351 to your computer and use it in GitHub Desktop.
Save iRYO400/82fbda2ddf52f440a066c27fbe12f351 to your computer and use it in GitHub Desktop.
package com.kodelabs.boilerplate.domain.executor.impl;
import com.kodelabs.boilerplate.domain.executor.Executor;
import com.kodelabs.boilerplate.domain.interactors.base.AbstractInteractor;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* This singleton class will make sure that each interactor operation gets a background thread.
* <p/>
*/
public class ThreadExecutor implements Executor {
// This is a singleton
private static volatile ThreadExecutor sThreadExecutor;
private static final int CORE_POOL_SIZE = 3;
private static final int MAX_POOL_SIZE = 5;
private static final int KEEP_ALIVE_TIME = 120;
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<Runnable>();
private ThreadPoolExecutor mThreadPoolExecutor;
private ThreadExecutor() {
long keepAlive = KEEP_ALIVE_TIME;
mThreadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
keepAlive,
TIME_UNIT,
WORK_QUEUE);
}
@Override
public void execute(final AbstractInteractor interactor) {
mThreadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
// run the main logic
interactor.run();
// mark it as finished
interactor.onFinished();
}
});
}
/**
* Returns a singleton instance of this executor. If the executor is not initialized then it initializes it and returns
* the instance.
*/
public static Executor getInstance() {
if (sThreadExecutor == null) {
sThreadExecutor = new ThreadExecutor();
}
return sThreadExecutor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment