Skip to content

Instantly share code, notes, and snippets.

@fortraan
Last active January 27, 2019 19:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fortraan/19ace444cdaa16a02de44c2555014585 to your computer and use it in GitHub Desktop.
Save fortraan/19ace444cdaa16a02de44c2555014585 to your computer and use it in GitHub Desktop.
Lightweight asynchronous tasks for Java 1.9
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Lightweight lambda-based async. Tasks can be chained together using
* {@link #andThen(AsyncTask, long)}, with a delay between them.
*
* If you don't want arguments, make T {@link Void}, then pass null to
* {@link #execute(Consumer, Object)} as the second argument.
* If you don't want a return type, make R {@link Void}, then return null from the last task in the
* chain.
* @param <T> argument for first task in chain
* @param <R> return type
*/
@FunctionalInterface
public interface AsyncTask<T, R> {
AtomicInteger runningAsyncTasks = new AtomicInteger(0);
R run(T args);
/**
* Adds another task to be executed after a delay.
* @param task task to be executed
* @param delayMillis delay, in milliseconds
* @param <V> return type of the new task
* @return a new AsyncTask, consisting of the original task, a delay, and the task argument
*/
default <V> AsyncTask<T, V> andThen(AsyncTask<R, V> task, long delayMillis) {
Objects.requireNonNull(task);
return (T t) -> {
R r = run(t);
TimeUnit.MILLISECONDS.sleep(delayMillis);
return task.run(r);
};
}
/**
* Executes the AsyncTask with an optional callback.
* @param asyncCallback optional callback
* @param args argument for first task in chain. If the first task has no arguments, args should
* be null.
*/
default void execute(Consumer<R> asyncCallback, T args) {
new Thread(() -> {
R result = run(args);
runningAsyncTasks.decrementAndGet();
if (asyncCallback != null) {
asyncCallback.accept(result);
}
}, "Async Callback " + runningAsyncTasks.incrementAndGet()).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment