RE: JavaMemoryModel: Thread starting in constructors

From: David Holmes (
Date: Tue Mar 12 2002 - 01:15:05 EST

Jeremy Manson wrote:
> I know this is taking your comment out of context, but wouldn't such a
> restriction kill some optimizations? For example (warning - contrived
> example) are you saying that in:
> class Foo {
> final int i;
> static Foo f;
> public Foo () {
> Foo g;
> g = this;
> i = 2;
> f = g;
> }
> }
> Compilers can't transform that to:
> public Foo() {
> f = this;
> i = 2;
> }
> because the original code has to be safe? Processors can't execute those
> instructions out of order, either?

In answer to the first question I'll say yes - the compiler can't do what
you suggest. It can of course do:

  public Foo() {
      i = 2;
      f = this;

And I'll be quite happy. The problem, of course, is context - the compiler
can't see what I'm doing to understand the difference between what I just
wrote and what you wrote, in terms of my program.

The difference between your contrived example and the original contrived
example, is that at least with "new Thread().start()" there is a
synchronization point between the two threads involved. So perhaps there is
something there that we can build on. Simply saying that publishing this at
the end of a constructor should be safe, is too broad and it does kill
simple optimisations. On the other hand, there need to be simple idioms for
publishing this that are guaranteed to do the right thing - in my opinion.

I'm not saying I have an answer, but this does make me very uncomfortable.

As for what the processor might do - I give up!


JavaMemoryModel mailing list -

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