Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Will a looping Thread.sleep() always run on the same physical core? [closed]

I'm trying to understand Java internals about their scheduling and thread affinity.

The question is:

given an infinite loop, running on a thread as such in a multicore environment (e.g. 8):

while(true) Thread.sleep(1000);
  1. Will this operation always run on the same physical thread or not?

  2. Is there some kind of affinity?

  3. If it doesn't always run on the same CPU, how does the JVM decide to actually switch the execution to a new CPU?

  4. Any way to verify this behavior?

like image 810
M4rk Avatar asked Jun 06 '26 17:06

M4rk


1 Answers

The JVM (thankfully) is blissfully not responsible for scheduling thread times, because Java threads are isomorphic (that means 1:1) to native threads. Thus the operating system schedules when a Java thread runs, and the operating system manages thread affinity (and you must use native code if you wish to influence it in anyway). There is at least one library that provides such a mechanism, but I have never used it.

I say thankfully, because long ago, the JVM used green threads and managed them cooperatively. And it was a lot slower with regards to multiple cpus/cores.

like image 61
Elliott Frisch Avatar answered Jun 08 '26 07:06

Elliott Frisch