Tuesday, April 10, 2007


Okay, so I lied about the contents of my next post. I bet no one even notices. Anyone even reading these? Yeah, right.

I was asked a question about fairness. The notion of fairness is one where there are some number of individual entities trying to make progress (in our case, threads), and there is some level of guarantee that this will actually happen.

Java has no meaningful fairness guarantee. A Java virtual machine is allowed to let a thread hog all of the CPU time. If I have:

Thread 1:
while (true);

Thread 2:
System.out.println("Hi there!");

There is no guarantee that Thread 2 will actually ever print its message. This is so that Java implementors can create cooperative implementations, where context switching only happens when Thread.yield is called, or when blocking occurs.

(In point of fact, this applies almost exclusively to the Oracle Java server. The popular VM implementations from Sun and IBM are preemptive.)

You could even have a wait loop:

Thread 1:
while (!someBoolean) {
  try { wait(); } catch (InterruptedException e) {}

Thread 2:
someBoolean = true;

This might not even terminate, because wait() can wake up spuriously. The wait loop can sleep and wake up indefinitely, and never let the other thread proceed.

At some point, I will explain what this has to do with the Java memory model.

No comments: