Search code examples
javarunnableexecutorserviceexecutor

Executors not completing all the task


Hi I am trying to run below code, and after executor is terminated I am expecting the count of remaining task to be 0, but for some reason it's more then 100 when it satisfy below condition.

 while(executor.isTerminated()) {
                System.out.println("Total Task Remaining : " + ExecutorServiceExample.task.size());
                System.out.println("*** Executor Terminated ***");
                break;
            }

Code Snippet.

package test;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceExample {

    public static volatile Set<String> task = new HashSet<String>();

    public static void main(String args[]) {

        ExecutorService executor = Executors.newFixedThreadPool(2000);

        for (int i = 0; i < 10000; i++) {
            String name = "task#" + i;
            task.add(name);
            Runnable runner = new TaskPrint(name);
            executor.execute(runner);
        }

        try {
            executor.shutdown();
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
            if (executor.isTerminated()) {
                System.out.println("Total Task Remaining : " + ExecutorServiceExample.task.size());
                System.out.println("*** Executor Terminated ***");
            }
        } catch (InterruptedException ignored) {
        }
    }
}

class TaskPrint implements Runnable {

    private final String name;

    public TaskPrint(String name) {
        this.name = name;
    }

    public void run() {
        ExecutorServiceExample.task.remove(name);
    }
}

Something strange with the result based on the number of tasks.

Output for 100 tasks.

Total Task Remaining : 0
*** Executor Terminated ***

Output for 1000 tasks.

Total Task Remaining : 0
*** Executor Terminated ***

Output for 10000 tasks.

Total Task Remaining : -27
*** Executor Terminated ***

Output for 100000 tasks.

Total Task Remaining : 1205
*** Executor Terminated ***

Solution

  • HashSet is not thread safe. You can create a synchronizedSet with

    public static volatile Set<String> task = Collections.synchronizedSet(new HashSet<String>());