blue-sky
blue-sky

Reputation: 53916

Why is this code executing sequentially?

Below code :

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTest {

    private static int counter = 0; 
    private static ExecutorService executorService = Executors.newCachedThreadPool();
    private static List<Integer> intValues = new ArrayList<Integer>();

    public static void main(String args[]){
        for(int counter = 0; counter < 10; ++counter){
            intValues.add(testCallback());
        }

        for(int i : intValues){
            System.out.println(i);
        }

        System.exit(0);
    }

    public static Integer testCallback() {

        Future<Integer> result = executorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                counter += 1;
                Thread.sleep(500);
                return counter;
            }
        });

        try {
            return result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Outputs :

1
2
3
4
5
6
7
8
9
10

This program takes approx 5 seconds to run. I am trying to execute multiple invocations of testCallback method in a seperate thread so I would expect this method to run in 10 threads concurrently where each thread uses approx 500 miliseconds of time. So over all I expet the program to run in < 1 second.

Why is counter not being invoked in seperate threads concurrently ?

Upvotes: 1

Views: 122

Answers (1)

SLaks
SLaks

Reputation: 888223

result.get();

This is a blocking call that waits for the task to complete.

Therefore, you're waiting for each task to finish before starting the next one.

Upvotes: 10

Related Questions