At 8:00 PM -0500 3/11/02, Bill Pugh wrote:
>OK, this is just a simple example of something I'm trying to fine tune:
>
>class A {
> int x;
> final int y;
> public A(int a, int b) {
> x = a;
> y = b;
> new Thread() {
> public void run() {
> System.out.println("x = " + x + ", y = " + y);
> }}.start();
> }
> }
>
>Assume someone invokes new A(1,2). Which of the might occur?
OK, the expected answer is possible.
>a) prints x = 1, y = 2
Unfortunately, answer (d) is also possible under the existing semantics:
>d) prints x = 1, y = 0
At first, I was worried about (e), but it turns out that it isn't
possible. The concern was reading the this$0 field of the constucted
inner class, but that field is properly set.
>e) the thread started in the constructor throws a NullPointerException
So, before people get all tied in knots, let me preface this by
saying that I intend to change the semantics so that (d) can't
happen. But this is why I am changing the semantics at this late
stage.
The problem is that the new thread can run to completion before the A
object is completely constructed. The current semantics require that
for final fields, if a reference to the constructed object is
published before the object construction is complete, any other
thread must use synchronization to ensure that the construction is
complete before loading a reference to the object. In this case, that
isn't the case.
The problem is that final fields have two kinds of special semantics:
a) The semantics of reading the final field itself
b) The problem of reading fields/elements of the object
referenced by the value loaded from a final field.
In the existing semantics, the two are pretty tightly coupled, and to
make the second one work, you need to associate a lot of special
magic with constructors.
What I need to do is make sure that if you do something like start a
thread in a constructor, you can see the proper values for the final
field, although with no magic guarantee about (b). However, starting
the new thread imposing a synchronization ordering that will ensure
the visibility of the things you need to see.
Bill
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:38 EDT