0

I was just curious and written following code. On running code, console showed threads created. I noticed there were around 32k threads created. My question is, Why My windows 10 OS hanged and also could not stop forcefully with task manager. Since my machine has i7 processor, why OS didn't manage to run on other processes? I believe threads created by java program must have been in one of the processes.

I am a beginner to java. Kindly let me know what happens internally in above case?


package infiniteThreads;

public class Main {

    public static void main(String[] args) {
        while(true){
            Thread t = new Thread(new Work());
            t.start();
        }

    }

}

package infiniteThreads;

public class Work implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("inside " + Thread.currentThread().getName());
        }

    }

}
AUK
  • 21
  • 3
  • You have a while (true) loop that constantly creates and starts worker threads... This is not really a java issue more a coding syntax issue as this could arise in any language. – ZeldaZach Jul 06 '17 at 14:18
  • 1
    *"why OS didn't manage to run on other processes?"* If your code is not consuming 100% on all cores, it's because `System.out.println()` is `synchronized`, so only one thread at a time can print anything. It's like 32000 people trying to walk through a door. They are all waiting in line, or rather all bunched up around the door, pressing to get through. – Andreas Jul 06 '17 at 14:31
  • I would never used java again if it tried to be smart and set a limit on threads used. this is a perfectly ok situation , what java does, creates the thread and let OS decide what to do with them – nafas Jul 06 '17 at 14:59

1 Answers1

2

As far as java is concerned, it would be consuming all the processors and all CPU threads available on your system. But the limitation that you are hitting with your experiment here is an OS Level limitation which is around Handles could read more about the it here.

Maybe you could try fiddling things around with your system setup to try to get some more insights with your experiment could try this link.

y ramesh rao
  • 2,954
  • 4
  • 25
  • 39