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.

Advertisements

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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: