Sobes.tech
Senior

Where do these streams come from when using new Thread without restrictions?

sobes.tech AI

Answer from AI

When creating threads using new Thread without restrictions in Java, each thread is created by the operating system and consumes system resources: memory (thread stack), descriptors, and CPU time.

Threads are taken from the OS thread pool, but if they are created uncontrollably, then:

  • The number of threads may exceed the capabilities of the OS, leading to memory or resource exhaustion.
  • There will be high load on the thread scheduler, which will slow down the entire system.

Therefore, it is important to limit the number of threads created, for example, using ExecutorService with a fixed thread pool. This allows reusing threads and controlling the load.

Example of a correct approach:

ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
    executor.submit(() -> {
        // task
    });
}
executor.shutdown();

Thus, threads are not created infinitely but are reused from the pool.

Where do these streams come from when using new… - sobes.tech