lucene-java-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Nader, John P" <john.na...@cengage.com>
Subject RE: Immutable OpenBitSet?
Date Thu, 28 Apr 2011 14:21:22 GMT
I agree that Trejkaz's example is correct and consistent with both the JLS spec and "Java Concurrency
in Practice", by Goetz.  

Without synchronization, the final keyword is necessary to ensure all values set on a long[]
in a constructor are seen by other threads in the state they were when the constructor completed.
 This keyword allows java to insert the appropriate read barriers on the first read of the
object, without the overhead of read barriers repeatedly on every read of the object.

The object construction guarantees are not enough for the long[] because these only guarantee
you will see the initial array of zero's.  To guarantee safety on the subsequent writes to
the long[] during the OpenBitSet constructor, the final keyword ensure those writes will be
flushed to main memory when construction completes prior to any other thread getting a reference
to the object.

A value holder that holds a final reference to the OpenBitSet is definitely an option as it
offers that same protection.


-----Original Message-----
From: Trejkaz [mailto:trejkaz@trypticon.org] 
Sent: Thursday, April 28, 2011 8:45 AM
To: java-user@lucene.apache.org
Subject: Re: Immutable OpenBitSet?

On Thu, Apr 28, 2011 at 6:13 PM, Uwe Schindler <uwe@thetaphi.de> wrote:
> In general a *newly* created object that was not yet seen by any other
> thread is always safe. This is why I said, set all bits in the ctor. This is
> easy to understand: Before the ctor returns, the object's contents and all
> references like arrays are not seen by any other thread (that's guaranteed).

Section 17.5 of the JLS gives the following example:

    class FinalFieldExample {
      final int x;
      int y;
      static FinalFieldExample f;
      public FinalFieldExample() {
        x = 3;
        y = 4;
      }
      static void writer() {
        f = new FinalFieldExample();
      }
      static void reader() {
        if (f != null) {
          int i = f.x; // guaranteed to see 3
          int j = f.y; // could see 0
        }
      }
    }

Essentially, there is no guarantee that the work in the constructor
has been completed when another thread gets a reference to the object.
 To make the guarantee, use the final keyword.

It seems like this contradicts the claim above, but maybe I'm missing something.

TX

---------------------------------------------------------------------
To unsubscribe, e-mail: java-user-unsubscribe@lucene.apache.org
For additional commands, e-mail: java-user-help@lucene.apache.org

Mime
View raw message