Last active
October 6, 2017 12:08
-
-
Save witoldsz/50169339cc49f074f630 to your computer and use it in GitHub Desktop.
Special use-case ExecutorService which collects tasks for execution and invokes them all on #flush() method in current thread. Useful for setup tests, so one can gain control of code execution scheduled by classes under test.
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
import java.util.ArrayDeque; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Queue; | |
import java.util.concurrent.AbstractExecutorService; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* | |
* @author witoldsz | |
*/ | |
public class OnDemandExecutorService extends AbstractExecutorService { | |
private final Queue<Runnable> commands = new ArrayDeque<>(); | |
@Override | |
public void shutdown() { | |
//noop | |
} | |
@Override | |
public List<Runnable> shutdownNow() { | |
return new ArrayList<>(commands); | |
} | |
@Override | |
public boolean isShutdown() { | |
return false; | |
} | |
@Override | |
public boolean isTerminated() { | |
return false; | |
} | |
@Override | |
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { | |
return true; | |
} | |
@Override | |
public void execute(Runnable command) { | |
commands.add(command); | |
} | |
public void flush() { | |
Runnable command; | |
while ((command = commands.poll()) != null) { | |
command.run(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment