RE: JavaMemoryModel: Thread starting in constructors

From: Joe Emporium (joe_emporium@yahoo.com)
Date: Mon Mar 11 2002 - 23:23:59 EST


To ensure "a) prints x = 1, y = 2", we can:

class A {
         int x;
         final int y;
         public A(int a, int b) {
                synchronized(this) {
                 x = a;
                 y = b;
                 new Thread() {
                     public void run() {
                                synchronized(A.this) {
                         System.out.println("x = " + x + ", y = " + y);
                                }
                         }}.start();
                 }
                }
         }

Hanson

> -----Original Message-----
> From: owner-javamemorymodel@cs.umd.edu
> [mailto:owner-javamemorymodel@cs.umd.edu]On Behalf Of David Holmes
> Sent: Monday, March 11, 2002 9:48 PM
> To: jmm
> Subject: RE: JavaMemoryModel: Thread starting in constructors
>
>
> Okay I'll bite.
>
> Bill Pugh wrote:
> > Assume someone invokes new A(1,2). Which of the might occur?
> >
> > a) prints x = 1, y = 2
>
> Geez I hope this one might! :)
>
> > b) prints x = 0, y = 0
> > c) prints x = 0, y = 2
> > d) prints x = 1, y = 0
>
> Hmmm. *If* the three statements can be arbitrarily reordered, and
> if the new
> thread could preempt the current one immediately, then yes to all of the
> above.
>
> > e) the thread started in the constructor throws a NullPointerException
>
> No. Presumably this is referring to the synthetic reference to the A
> instance? The Thread constructor must execute to completion before start()
> is called and the synchronization inherent in start() guarantees that the
> new thread sees what it parent did. So no NPE is possible.
>
> You know, all this makes me *very* uncomfortable. It *should* be safe to
> publish "this" as the last action in a constructor.
>
> David
>
> -------------------------------
> JavaMemoryModel mailing list -
> http://www.cs.umd.edu/~pugh/java/memoryModel

-------------------------------
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