Created
May 15, 2014 20:26
-
-
Save Arnauld/e0dd490671a46694ce92 to your computer and use it in GitHub Desktop.
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
package sequencer; | |
import java.util.Queue; | |
import java.util.concurrent.ConcurrentLinkedQueue; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.atomic.AtomicBoolean; | |
import java.util.function.Supplier; | |
/** | |
* @author <a href="http://twitter.com/aloyer">@aloyer</a> | |
*/ | |
public class Sequencer { | |
private final ExecutionUnit executionUnit; | |
private final AtomicBoolean shutdown = new AtomicBoolean(); | |
public Sequencer(Supplier<ExecutorService> executor) { | |
this.executionUnit = new ExecutionUnit(executor); | |
} | |
public void dispatch(Runnable runnable) { | |
executionUnit.dispatch(runnable); | |
} | |
private static class ExecutionUnit implements Runnable { | |
private final Queue<Runnable> queue = new ConcurrentLinkedQueue<>(); | |
private final Supplier<ExecutorService> executor; | |
private volatile boolean isRunning = false; | |
public ExecutionUnit(Supplier<ExecutorService> executor) { | |
this.executor = executor; | |
} | |
public synchronized void dispatch(Runnable runnable) { | |
queue.add(runnable); | |
if (!isRunning) { | |
dispatchNext(); | |
} | |
} | |
public synchronized void taskDone() { | |
isRunning = false; | |
dispatchNext(); | |
} | |
private synchronized void dispatchNext() { | |
if (queue.isEmpty()) | |
return; | |
isRunning = true; | |
executor.get().submit(this); | |
} | |
private void executeNextTask() { | |
try { | |
Runnable runnable = queue.poll(); | |
if (runnable != null) | |
runnable.run(); | |
} catch (Exception ie) { | |
exceptionPolicyHandle(ie); | |
} | |
} | |
@Override | |
public void run() { | |
try { | |
executeNextTask(); | |
} catch (Exception ex) { | |
exceptionPolicyHandle(ex); | |
} finally { | |
taskDone(); | |
} | |
} | |
private void exceptionPolicyHandle(Exception ex) { | |
// ignore and continue to next task ? | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic testing,
nbThreads=4