Wednesday, December 14, 2016

Task execution in different ways with Java

Task execution in different ways


public class ExecuteTask {
public static void main(String[] args) {
// Runs in the main thread
helloWorld();
// Runs in a new thread
new Thread(ExecuteTask::helloWorld).start();
// Runs in the default fork join pool
ForkJoinPool.commonPool().submit(ExecuteTask::helloWorld);
// Runs in the default fork join pool via a CompletableFuture
CompletableFuture.runAsync(ExecuteTask::helloWorld);
// Runs in a custom fork join pool (with three workers)
new ForkJoinPool(3).submit(ExecuteTask::helloWorld);
// Queues up task in a single thread executor
Executors.newSingleThreadExecutor().execute(ExecuteTask::helloWorld);
// Caches tasks so that short lived re-occurring tasks can execute faster
Executors.newCachedThreadPool().execute(ExecuteTask::helloWorld);
// Runs in a separate thread pool with the given delay
Executors.newScheduledThreadPool(2).schedule(ExecuteTask::helloWorld, 10, TimeUnit.MILLISECONDS);
}
public static void helloWorld() {
System.out.println("Hello World greeting from " + Thread.currentThread().getName());
}
}