Skip to content

Instantly share code, notes, and snippets.

@mingshun
Last active March 4, 2017 09:00
Show Gist options
  • Save mingshun/5c9239759b658d74148077ff493e4786 to your computer and use it in GitHub Desktop.
Save mingshun/5c9239759b658d74148077ff493e4786 to your computer and use it in GitHub Desktop.
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class LoopExecutorService {
private int nThreads;
private TaskFactory factory;
private LoopExecutor executor;
private boolean started = false;
public LoopExecutorService(int nThreads, Runnable task) {
this(nThreads, () -> task);
}
public LoopExecutorService(int nThreads, TaskFactory factory) {
this.nThreads = nThreads;
this.factory = factory;
executor = new LoopExecutor(nThreads);
}
public synchronized void start() {
if (started) {
return;
}
for (int i = 0; i < nThreads; i++) {
executor.execute(factory.newTask());
}
started = true;
}
public void stop() {
executor.shutdown();
}
public int awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
if (!executor.isTerminated()) {
throw new IllegalStateException("LoopExecutor has not been terminated yet.");
}
if (executor.awaitTermination(timeout, unit)) {
return 0;
}
return executor.getActiveCount();
}
public interface TaskFactory {
Runnable newTask();
}
private class LoopExecutor extends ThreadPoolExecutor {
public LoopExecutor(int nThreads) {
super(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
this.execute(factory.newTask());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment