Adam Kotwasinski
Adam Kotwasinski

Reputation: 4554

JVM fairness while scheduling threads

Are there any assumptions on how fair JVM is when it comes to scheduling threads for execution?

For the below snippet, is it possible to have "code A" executed only, with B being ignored?

public static void main(String args[]) {

    new Thread() {
      public void run() {
        for (;;) { /* code A */ }
      }
    }.start();

    new Thread() {
      public void run() {
        for (;;) { /* code B */ }
      }
    }.start();

}

The question is more of a theoretical one - let's assume that neither of the threads gets blocked or otherwise encourages scheduler to switch context.

Upvotes: 3

Views: 574

Answers (1)

Stephen C
Stephen C

Reputation: 718826

Are there any assumptions on how fair JVM is when it comes to scheduling threads for execution?

No.

For the below snippet, is it possible to have "code A" executed only, with B being ignored?

In theory yes.

In practice:

  • if there was one (available) core, I would expect the OS-level thread scheduler to time-slice the threads so that they each got roughly 50% of the available time in the log term

  • if there were multiple (available) cores, I would expect the two threads to run in parallel.


Note that neither the JLS or the JVM spec says anything about thread scheduling or fairness. Neither does the javadoc for Thread.

To my knowledge, the only Java API that mentions fairness is the ReentrantLock API (javadoc) where there is a constructor parameter for creating a lock with a fairness policy. This means that the scheduler favors the thread that has been waiting the longest on the lock. But even this is caveated:

"Note however, that fairness of locks does not guarantee fairness of thread scheduling."

Upvotes: 3

Related Questions