For loop keeps stopping

Not sure if I am doing something wrong here:

I am doing a simple for loop in which i submit tasks to a fixed thread executor pool.

Here’s the basic code, though i have created a full project which displays exactly what my problem is (on my machine with i7-4800MQ) here: https://github.com/TheBestPessimist/kotlin-for-loop-keeps-stopping


val counter = AtomicInteger()
fun t() {
    val executor = Executors.newFixedThreadPool(3) // i have 4 core machine
    for (i in 1..10_000_000_000_000L) {
        executor.submit {
            val c = counter.incrementAndGet()
            if (c % 100 == 0) {
                println("====" + Instant.now() + "=======" + c)
            }
        }
    }
    executor.shutdown()
}

The problem is that the println in the output keeps stopping for 0.5 ~ 2.5 seconds from time to time, without any apparent reason, and the continues like nothing happened.


This happens on windows 10, jdk1.8.0_152 x64.

You are shutting down executor before it finishes working. Remove shutdown.

That still doesn’t fix the problem. (i am not using shutdownNow)

You can see that the println line is inside the submit therefore, since the printing still continues (after the problematic pauses) the executor is not stopping yet.


L.E:

Not even awaiting helps:

executor.shutdown()
executor.awaitTermination(1, TimeUnit.DAYS)

The behavior you are describing indicates issues with memory and garbage collection. Looking at your code, this is not that surprising.

Even though your thread pool will have at most 3 threads, it still has an open-ended queue for the submitted tasks, from which you create a really huge number.

When your code stops printing, it is likely due to a stop-the-world garbage collection phase.

1 Like