Re: JavaMemoryModel: Thread starting in constructors

From: Jerry Schwarz (
Date: Tue Mar 12 2002 - 12:51:24 EST

At 08:54 AM 3/12/2002, Cliff Click wrote:
>Jerry Schwarz wrote:
>>That was my reaction too, but I slept on it overnight and I think I see a
>>subtlety that I overlooked yesterday. When is A.y read? Could it be read
>>by the constructor of the Thread instead of by the run method.
>>This question can be illustrated without threads. Consider the following
>> public class S {
>> public final int x;
>> S() { x = ... ; }
>> ...
>> }
>> public class U {
>> private S s;
>> public U(S s) { this.s = s; }
>> public int f() { return s.x; }
>> }
>>Is a compiler allowed to transform the definition of U into
>> public class U' {
>> private int s_x;
>> public U(S s) { this.s_x = s.x ; }
>> public int f() { return s_x; }
>> }
>>Obviously, this couldn't be allowed if s.x were not final, but does the
>>special semantics of final allow it? I would like to say yes because
>>this is potentially a significant optimization. The relevance to Bill's
>>example is that if this transformation were allowed on the anonymous
>>Thread class then
>>> d) prints x = 1, y = 0
>>becomes possible.
>>But so do other anomalies. In particular what if U's are used in
>>constructors of S. Let's modify S a little
>> public class S {
>> public final int x;
>> private U u;
>> public S() {
>> u = new(this);
>> x = ...; // non-zero value
>> }
>> public int f() { return u.f(); }
>> }
>>With the optimization in place S.f will return 0. But I don't see any
>>way I can justify S.f returning 0, so I guess the optimization can't be
>>allowed. And so, (d) isn't allowed either.
>> -- Jerry Schwarz
>>JavaMemoryModel mailing list -
>Now you are asking for the allowed optimizations when we inline into a
>constructor BEFORE a final is set and then want to eagerly read the final.
>This is an easy-to-test-for situation (inlining into a constructor before
>setting all finals) with an obvious optimization to cut out (hoisting the
>read of the final into U's constructor). I'm happy to give up this

My proposed optimization had nothing to do with inlining. It was a proposed
transformation of the methods of U that you might want to perform on U and
have effective for all invocations of methods of U.

On reflection I realize that the proposed optimization might interact
poorly with reflection in the language (pun intended:-) because it is
changing the fields of the class. So maybe it isn't allowed for that reason.

>Dr. Cliff Click Chief Architect, HotSpot Server Sun Microsystems, Inc.
>Cliff.Click@Sun.COM Senior Staff Engineer 4150 Network Circle
>(408) 276-7046 MS USCA14-102 Santa Clara, CA 95054
>JavaMemoryModel mailing list -

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:38 EDT