0

I am new in concurrency in Java, but I have problems in understanding the work of the executor service.

My problem: I'm executing below code separately and I wonder that array of threads faster then executor service (3s vs 30s, by System.currentTimeMillis()).

public class SimpleExample {
private static final int THREAD_COUNT = 10;
private final AtomicInteger cnt;

private SimpleExample() {
    cnt = new AtomicInteger();
    cnt.set(0);
}

public static void main(String[] args) throws IOException, InterruptedException {
    // threads();
    // service();
}

private static void threads() throws InterruptedException {
    SimpleExample example = new SimpleExample();
    ParallelTask task = new ParallelTask(example);
    Thread[] threads = new Thread[THREAD_COUNT];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(task);
    }

    long a = System.currentTimeMillis();
    for (Thread thread : threads) {
        thread.start();
    }

    for (Thread thread : threads) {
        thread.join();
    }
    System.out.println("time: " + (System.currentTimeMillis() - a));
}

private static void service() {
    SimpleExample example = new SimpleExample();
    ParallelTask task = new ParallelTask(example);
    ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);

    long a = System.currentTimeMillis();
    Future future = service.submit(task);
    while (!future.isDone()) {
        // do nothing
    }
    service.shutdown();
    System.out.println("time: " + (System.currentTimeMillis() - a));
}

void run() {
    while (cnt.get() < 300) {
        try {
            Thread.sleep(100);
            System.out.println(cnt.get());
            cnt.incrementAndGet();
        } catch (InterruptedException ignore) {}
    }
}

static class ParallelTask implements Runnable {
    private final SimpleExample example;

    ParallelTask(SimpleExample example) {
        this.example = example;
    }

    @Override
    public void run() {
        example.run();
    }
}

}

How it's possible? Thanks.

clhost
  • 33
  • 1
  • 4
  • As the linked duplicate describes, you cannot easily compare execution times in Java without serious preparation. Also, `currentTimeMillis` is the wrong tool for the job. – Jim Garrison Apr 23 '18 at 17:34
  • But the question is not about the benchmark, here and without it it is clear that the executor service is slower. Why? – clhost Apr 23 '18 at 17:36
  • 3
    In the `threads` method you start 10 threads in parallel, each one doing about 1/10 the work. In the `service` method you submit just one job, which has to do all the work. – Thomas Kläger Apr 23 '18 at 17:36
  • Thomas Kläger thank you – clhost Apr 23 '18 at 17:40

0 Answers0