deadend
deadend

Reputation: 1376

Java Executor Service Is Not Processing Parallely

I am attempting to run multiple services parallely using ExecutorService. But i failed to execute parallely.

I have written java.util.concurrent.TimeUnit.MINUTES.sleep(1) to wait one minute in Service1 class.

But Service2 is processing only after Service1 processed.

Below is my code snippet, Kindly correct me/code if my understand about ExecutorService is wrong

public void startService() {

    try {
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.submit(new Service1());
        service.submit(new Service2());
        service.submit(new Service3());

        service.shutdown();
        service.awaitTermination(1, TimeUnit.MINUTES);

        System.exit(0);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public class Service1 implements Callable<Object> {

    {
        try {
            java.util.concurrent.TimeUnit.MINUTES.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object call() throws Exception {
        return null;
    }
}

public class Service2 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        System.out.println(" Service 2 "); // It prints after 1 minute only.
        return null;
    }
}

public class Service3 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        System.out.println(" Service 3 "); 
        return null;
    }
}

Upvotes: 0

Views: 96

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 9650

The code:

{
    try {
        java.util.concurrent.TimeUnit.MINUTES.sleep(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

is a constructor, and it is called by the main thread when it's doing new Service1(). So yeah, it must complete before it has a chance to submit the services.

UPDATE:

In your original post, the sleep was in the call method, and it worked. Now, your Service1 is equivalent to:

public class Service1 implements Callable<Object> {

    public Service1() {
        try {
            java.util.concurrent.TimeUnit.MINUTES.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object call() throws Exception {
        return null;
    }
}

And only the call method is run by the executor. the Service1 instance cannot even be submitted before the constructor completes.

Upvotes: 2

Related Questions