#476 Execution Time of Exercises in ThreadPoolExecutor

Companies:
Alfa-Bank
Themes:
JavaConcurrencyCode Review

How long will the program take on a machine with 1 CPU and no HT?

static void sleepOneSecond() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

public static void main(String[] args) {
    try (var pool = new ThreadPoolExecutor(
                        /*core pool size*/ 2,
                        /*maximum pool size*/ 10,
                        /*keepAliveTime value and unit*/ 30,
                        TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(10))) {
        var start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            pool.execute(Pool::sleepOneSecond);

            // what about this?
            /*
            var t = new Thread(Pool::sleepOneSecond);
            t.setDaemon(true);
            pool.execute(t);
            */
        }
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
                log.info("Time taken: " + (System.currentTimeMillis() - start))));
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in