Running a task on a different thread in Java 8

Occasionally it can be worth putting a task on a different thread so that it doesn’t block the main thread. Examples include a task that analyses heavy files, a task that sends out emails etc. If we put these tasks on a different thread and don’t wait for it to return a result then it’s called the fire-and-forget pattern. We start a new thread and let it run in the background. The task on the different thread is expected to carry out its functions independently of the main thread.

Let’s imagine that the following greetCustomer method is something we want to run on separate thread so that the main thread is not blocked:

public class CustomerService
{
    public void greetCustomer()
    {
        System.out.println("Good morning!");
    }
}

Since the introduction of the Runnable and ThreadPoolExecutor classes in Java 7 we know that an optimal way is to implement the Runnable interface and submit it to a thread pool for execution. Here’s a possible solution:

public class CustomerGreeterTask implements Runnable
{
    private final CustomerService customerService;

    public CustomerGreeterTask(CustomerService customerService)
    {
        this.customerService = customerService;
    }    
    
    @Override
    public void run()
    {
        System.out.println("About to run the customer greeter from a Runnable");
        customerService.greetCustomer();
    }   
}

All we need to do is override the run method of the interface.

We can easily get hold of a thread pool using the Executors class which has built-in methods to get hold of thread pools for various uses:

  • newCachedThreadPool: “Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.” It is mainly used for short and light-weight background tasks
  • newFixedThreadPool: “Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.” This is most often used for heavier methods that are not called too often

Here’s how to submit a Runnable to an executor:

CustomerService customerService = new CustomerService();
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
newCachedThreadPool.submit(new CustomerGreeterTask(customerService));

Java 8 and its lambdas makes this even easier:

newCachedThreadPool.submit(() -> customerService.greetCustomer());

That’s it!

View all posts related to Java here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: