Getting the result of the first completed parallel task in Java

In this post we saw how to delegate one or more parallel tasks to different threads and wait for all of them to complete. We pretended that 4 different computations took 1,2,3 and respectively 4 seconds to complete. If we execute each calculation one after the other on the same thread then it takes 10 seconds to complete them all. We can do a lot better by assigning each operation to a separate thread and let them run in parallel. The Future and Callable of T objects along with a thread pool make this very easy to implement.

There are situations where we only need the result from 1 parallel operation. Imagine that it’s enough to complete 1 of the four computations in the example code so that our main thread can continue. We don’t know how long each operation will take so we let them have a race. The one that is executed first returns its value and the rest are interrupted and forgotten. We’ll see how to achieve that in this post.

We’ll reuse the same CalculationService interface and its 4 implementations from the post referenced above: AdditionService, SubtractionService, MultiplicationService and DivisionService. When we waited for all of them to complete it took 4 seconds for the thread pool to return them which corresponds to the 4 seconds it took the DivisionService to complete its task. Our expectation now is that AdditionService should win since it only needs 1 second to return. The ExecutorCompletionService can help us with the implementation. ExecutorCompletionService has a generic form where we can declare the expected return type. Without specifying the type we get an Object back.

Here’s an example:

private static void waitForFirstThreadCompletion()
{
    CalculationService adder = new AdditionService();
    CalculationService subtractor = new SubtractionService();
    CalculationService multiplier = new MultiplicationService();
    CalculationService divider = new DivisionService();
    int firstOperand = 10;
    int secondOperand = 5;

    Instant start = Instant.now();

    ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
    ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService(newCachedThreadPool);
    List<Callable<Integer>> calculationTasks = new ArrayList<>();
    calculationTasks.add(() -> divider.calculate(firstOperand, secondOperand));
    calculationTasks.add(() -> subtractor.calculate(firstOperand, secondOperand));
    calculationTasks.add(() -> multiplier.calculate(firstOperand, secondOperand));    
    calculationTasks.add(() -> adder.calculate(firstOperand, secondOperand));

    calculationTasks.stream().forEach((calculationTask)
            -> 
            {
                completionService.submit(calculationTask);
    });

    try
    {
        Integer firstResult = completionService.take().get();
        System.out.println(firstResult);
    } catch (InterruptedException | ExecutionException | NullPointerException ex)
    {
        System.err.println(ex.getMessage());
    }

    Instant finish = Instant.now();
    Duration duration = Duration.between(start, finish);
    long seconds = duration.getSeconds();

    System.out.println(seconds);
}

The take() method of the completion service will wait until the first completed task has returned. Note that the order of the tasks doesn’t matter, the addition service will win the race. The above example block will complete in 1 second as expected.

The completion service has a poll() method as well. It returns null if none of the submitted tasks has returned. Thus it’s necessary to to check for nulls in a loop like in the following example:

boolean firstCompleted = false;
while (!firstCompleted)
{
    try
    {
        Future<Integer> future = completionService.poll();
        if (future != null)
        {
            Integer firstResult = future.get();
            System.out.println(firstResult);
            firstCompleted = true;
        }
    } catch (NullPointerException | InterruptedException | ExecutionException ex)
    {
        System.err.println(ex.getMessage());
    }
}

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

Elliot Balynn's Blog

A directory of wonderful thoughts

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: