task4java is a framework to compose and execute code asynchronously. Its features are:
- lightweight
- high performance
- based on standard Java libraries (Java V1.6 and above)
- Android compatible
- Lambda compatible (Java V1.8)
The key concept is based on JS promises (e.g. when.js) or Microsoft .NET Task Parallel Library (TPL).
The major class of this framework is the Task class which is based on the Java FutureTask class.
The following code will show the execution of three code blocks in series.
Task<String> taskResult = TaskFactory.startNew(new Callable<String>() {
@Override
public String call() throws Exception {
// Schedule a new task on the default thread pool
Logger.instance.d(TAG, "Thread for task1: " + Thread.currentThread().getId());
Thread.sleep(1000);
return "Ready";
}
}).continueWith(new CallableTask<String, String>() {
@Override
public String call(Task<String> task) throws Exception {
// Execute this code after the previous task has finished
Logger.instance.d(TAG, "Thread for step1: " + Thread.currentThread().getId());
return task.get() + " step1";
}
}).continueWith(new CallableTask<String, String>() {
@Override
public String call(Task<String> task) throws Exception {
// Execute this code after the previous task has finished
Logger.instance.d(TAG, "Thread for step2: " + Thread.currentThread().getId());
return task.get() + " step2";
}
});
// blocks until the result is available
System.out.println(taskResult.get());
To change the executor of the tasks the continueWith
method is overloaded with the following signatures:
public <VNew> Task<VNew> continueWith(CallableTask<VNew, V> callableTask);
public <VNew> Task<VNew> continueWith(CallableTask<VNew, V> callableTask, Executor executor)
Hence each Executor can be used to start the tasks. The TaskFactory class contains some executor services but you can create your own executor if necessary.
Licensed under Apache license 2.0. Full license here »