|
Constructors, values and threads: msg#00067lang.scala
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 |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: schama2src: 00067, Burak Emir |
|---|---|
| Next by Date: | RE: addJavaBeanMethods: 00067, Judson, Ross |
| Previous by Thread: | eclipse plugin for scala version 2i: 00067, Molnár Balázs |
| Next by Thread: | Rewriting introduction mixin example for Scala2: 00067, Gabriel Riba |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |