Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this my attempt of spawning endless Threads stopping at 4?

I have this simple code in Java 8:

class ThreadTest {
    void threadTest() {
        new Thread(this::threadTest).start();
        System.out.println(Thread.activeCount());
    }

    public static void main(String[] args) {
        new ThreadTest().threadTest();
    }
}

and I was pretty much expecting to see very large numbers getting printed. All I see in the console is:

4
4
4
4
4
4
4
4
4

I said maybe I am not able to see others for whatever reason and modified the code as below:

class ThreadTest {
    void threadTest() {
        new Thread(this::threadTest).start();
        if (Thread.activeCount() > 4) {
            System.out.println(Thread.activeCount());
        }
    }

    public static void main(String[] args) {
        new ThreadTest().threadTest();
    }
}

and now nothing gets printed.

What am I missing here?

like image 532
Koray Tugay Avatar asked Oct 27 '18 20:10

Koray Tugay


People also ask

What happens if you spawn too many threads?

You need to prevent too many threads from being spawned, a problem that could potentially result in a denial of service owing to exhausted system resources.

How many threads can we spawn?

Each CPU core can have up to two threads if your CPU has multi/hyper-threading enabled. You can search for your own CPU processor to find out more.

How many threads can be executed at a time?

Only 1 native CPU thread can be executed at a time by 1 single core. If for example you have 4 cores, only 4 threads can be executed at the same time (if you have 2 thread/core still one will execute at a time, next will wait to be executed as soon as first finish).

How many threads can I run Python?

The truth is, you can run as many threads in Python as you have memory for, but all threads in a Python process run on a single machine core, so technically only one thread is actually executing at once. What this means is that Python threads are really only useful for concurrent I/O operations.


1 Answers

Once your thread reaches the end of its execution (in your case, the end of the threadTest() method), it is no longer an active thread.

If you add an excessively long Thread.sleep in your method, you will see this active thread count increase further.

like image 156
Joe C Avatar answered Oct 07 '22 23:10

Joe C