Why does “while(true)” without “Thread.sleep” cause 100% CPU usage on Linux but not on Windows?

JavaLinuxWindowsMultithreadingCpu Usage

Java Problem Overview


I have created a simple program in java:

public static void main(String[] args) throws InterruptedException {
    while (true) 
        ;
}

If I run this on a Linux machine, it shows 100% CPU usage, but doesn't cause the OS to appear slow. However, if I run the exact same code on Windows, it only shows about 20% CPU usage.

I am using Oracle JRE on Windows and OpenJDK 6 on Linux.

I'm wondering if Windows' scheduler preempt threads randomly and Linux's doesn't?

Java Solutions


Solution 1 - Java

By default, top on Linux runs in so-called IRIX mode, while the Windows Task Manager does not. Let's say you have 4 cores:

  • With IRIX mode on, 1 fully utilized core is 100% and 4 cores are 400%.

  • With IRIX mode off, 1 fully utilized core is 25% and 4 cores are 100%.

This means that by default, top on Linux will show an infinite loop as ~100% and Windows will show it as ~25%, and it means exactly the same thing.

You can toggle IRIX mode while top is running with Shift+i. This will make the numbers match up.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManiekView Question on Stackoverflow
Solution 1 - Javathat other guyView Answer on Stackoverflow