commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Oliver Heger <oliver.he...@oliver-heger.de>
Subject Re: svn commit: r819141 - in /commons/proper/lang/trunk/src: java/org/apache/commons/lang/concurrent/LazyInitializer.java test/org/apache/commons/lang/concurrent/ test/org/apache/commons/lang/concurrent/LazyInitializerTest.java
Date Sat, 26 Sep 2009 14:58:57 GMT
sebb schrieb:
> On 26/09/2009, oheger@apache.org <oheger@apache.org> wrote:
>> Author: oheger
>>  Date: Sat Sep 26 14:27:32 2009
>>  New Revision: 819141
>>
>>  URL: http://svn.apache.org/viewvc?rev=819141&view=rev
>>  Log:
>>  [LANG-496] Added LazyInitializer class plus test class.
>>
>>  Added:
>>     commons/proper/lang/trunk/src/java/org/apache/commons/lang/concurrent/LazyInitializer.java
  (with props)
>>     commons/proper/lang/trunk/src/test/org/apache/commons/lang/concurrent/
>>     commons/proper/lang/trunk/src/test/org/apache/commons/lang/concurrent/LazyInitializerTest.java
  (with props)
> 
> <snip/>
> 
>>  +    /** Stores the managed object. */
>>  +    private volatile T object;
>>  +
>>  +    /**
>>  +     * Returns the object wrapped by this instance. On first access the object
>>  +     * is created. After that it is cached and can be accessed pretty fast.
>>  +     *
>>  +     * @return the object initialized by this {@code LazyInitializer}
>>  +     */
>>  +    public T get() {
>>  +        T result = object;
>>  +
>>  +        if (result == null) {
>>  +            synchronized (this) {
>>  +                result = object;
>>  +                if (result == null) {
>>  +                    object = result = initialize();
>>  +                }
>>  +            }
>>  +        }
>>  +
>>  +        return result;
>>  +    }
> 
> Is the temporary variable "result" needed?
> Would it not be simpler to do the following:
> 
> private volatile T object;
> 
> public T get() {
>       if (object == null) {
>          synchronized (this) {
>              if (object == null) {
>                  object = initialize();
>              }
>          }
>      }
>    return object;
> }
> 
> Or maybe I'm missing some subtlety here ?
> In which case it should be documented in a comment please.
> 
> <snip/>
> 

According to Bloch's book the temporary variable is indeed a performance 
optimization. It prevents that the volatile field is read twice in the 
common case that the object has already been initialized.

It's a good idea to add a comment. Will do.

Oliver

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@commons.apache.org
For additional commands, e-mail: dev-help@commons.apache.org


Mime
View raw message