Over a million developers have joined DZone.

Java Holiday Calendar 2016 (Day 14): Submitting a Task

DZone 's Guide to

Java Holiday Calendar 2016 (Day 14): Submitting a Task

These days, Java developers have a variety of means to execute tasks. From threads to join pools to caching, you have no shortage of options.

· Java Zone ·
Free Resource

Image title

Today's tip is about submitting tasks. Historically, we Java developers commonly used a new Thread directly when we wanted something to be done in parallel with the current thread. These days, there are a number of other, better, and more convenient ways of getting the job done.

For the sake of simplicity, we assume that we have a task we want to run that does not return something. This can be modeled using the Runnable interface, and we can use lambdas to express our tasks.

Here are a number of alternate ways to execute a task:

public class Main {
    public static void main(String[] args) {

        // Runs in the main thread 

        // Runs in a new thread
        new Thread(Main::helloWorld).start();

        // Runs in the default fork join pool

        // Runs in the default fork join pool via a CompletableFuture

        // Runs in a custom fork join pool (with three workers)
        new ForkJoinPool(3).submit(Main::helloWorld)

        // Queues up task in a single thread executor

        // Caches tasks so that short lived re-occurring tasks can execute faster

        // Runs in a separate thread pool with the given delay
        Executors.newScheduledThreadPool(2).schedule(Main::helloWorld, 10, TimeUnit.MILLISECONDS);

    public static void helloWorld() {
        System.out.println("Hello World greeting from " + Thread.currentThread().getName());

This will produce the following print out:

Hello World greeting from main

Hello World greeting from Thread-0

Hello World greeting from ForkJoinPool.commonPool-worker-1

Hello World greeting from ForkJoinPool.commonPool-worker-1

Hello World greeting from ForkJoinPool-1-worker-1

Hello World greeting from pool-1-thread-1

Hello World greeting from pool-2-thread-1

Hello World greeting from pool-3-thread-1

Remember that in a real scenario, we need to shut down the custom thread pools we are creating, or else our program will not terminate properly (because there are still live threads hanging around). Closing a thread pool can be done like this:

try {
     forkJoinPool.awaitTermination(1, TimeUnit.HOURS);

} catch (InterruptedException ie) {

Read more on thread executing principles on DZone here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream-based ORM tool and runtime. Please check it out on GitHub.

java ,task ,lambda ,threads

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}