Constructors, values and threads

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Constructors, values and threads

Judson, Ross
Ran into a tricky bit earlier today that I thought I'd write down so it
won't get lost.  Consider:

object FutureTest {
  import scalax.future.Future._;
  val random = new java.util.Random();
  val check = spawn { 22 + random.nextInt(25) };
  Console.println(check());
}

This will lock and never print.  The expression "22 +
random.nextInt(25)" results in an Object.wait() call when getting the
value of "random".  This wait is _internal_ to the Java VM; the VM will
not allow any call to the object until it has been fully constructed.
The spawn has created another thread to evaluate the expression, but as
a part of FutureTest's constructor it is waiting for the result of that
spawn.  The spawned thread gets held up in a wait because FutureTest
isn't yet constructed.

Changing the code to the following works:

Object FutureTest {
  go;
  import scalax.future.Future._;
  def go = {
    val random = new java.util.Random();
    val check = spawn { 22 + random.nextInt(25) };
    Console.println(check());    
  }
}

In this example we are no longer calling the "random" method/value on
the FutureTest object prior to its complete construction; random is a
local value.

The operative part of the Java VM spec is:

http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5

Code generation for the Java VM may want to take this additional
"hidden" synchronization point into account somehow...or have it
documented at the language level.

RJ