Java CompletionService example

Friday, December 4th, 2020

Main.java

package com.lstierneyltd;

public class Main {
    public static void main(String[] args) throws Exception {
        final CompletionServiceExample completionServiceExample = new CompletionServiceExample();
        completionServiceExample.runDemo();
    }
}

CompletionServiceExample.java

package com.lstierneyltd;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class CompletionServiceExample {
    private static final int NUMBER_OF_THREADS = 3;
    private final List<Callable<String>> callables = new ArrayList<>();
    private final ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public CompletionServiceExample() {
        initCallables();
    }

    public void runDemo() throws Exception {
        final long startTime = System.currentTimeMillis();

        processCallableTasks();

        System.out.println("That took " + (System.currentTimeMillis() - startTime)/1000 + " seconds");

        shutdownThreadPoolExecutor();
    }

    private Callable<String> getCallable(int id) {
        final Callable<String> callable = () -> {
            System.out.println("Starting Callable " + id);
            final long taskStartTime = System.currentTimeMillis();

            TimeUnit.MILLISECONDS.sleep(10000);

            System.out.println("CallableTask " + id + " took " + (System.currentTimeMillis() - taskStartTime)/1000 + " seconds");

            return "Callable completed";
        };
        return callable;
    }

    private void initCallables() {
        callables.add(getCallable(1));
        callables.add(getCallable(2));
        callables.add(getCallable(3));
    }

    private void processCallableTasks() throws InterruptedException, ExecutionException {
        final CompletionService<String> completionService = new ExecutorCompletionService<String>(threadPoolExecutor);

        for(Callable<String> callable : callables) {
            completionService.submit(callable);
        }

        int received = 0;
        while(received < NUMBER_OF_THREADS) {
            Future<String> resultFuture = completionService.take(); // blocks if none available
            String result = resultFuture.get();
            System.out.println("Future done " + result);
            received++;
        }
    }

    private void shutdownThreadPoolExecutor() {
        threadPoolExecutor.shutdown();
        try {
            if (!threadPoolExecutor.awaitTermination(800, TimeUnit.MILLISECONDS)) {
                threadPoolExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            threadPoolExecutor.shutdownNow();
        }
    }
}

Output

Starting Callable 1
Starting Callable 2
Starting Callable 3
CallableTask 3 took 10 seconds
CallableTask 1 took 10 seconds
CallableTask 2 took 10 seconds
Future done Callable completed
Future done Callable completed
Future done Callable completed
That took 10 seconds

You can leave a response, or trackback from your own site.

Tags: ,
Posted in: Development, Examples



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>