View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.concurrent;
18  
19  /**
20   * <p>
21   * This class provides a generic implementation of the lazy initialization
22   * pattern.
23   * </p>
24   * <p>
25   * Sometimes an application has to deal with an object only under certain
26   * circumstances, e.g. when the user selects a specific menu item or if a
27   * special event is received. If the creation of the object is costly or the
28   * consumption of memory or other system resources is significant, it may make
29   * sense to defer the creation of this object until it is really needed. This is
30   * a use case for the lazy initialization pattern.
31   * </p>
32   * <p>
33   * This abstract base class provides an implementation of the double-check idiom
34   * for an instance field as discussed in Joshua Bloch's "Effective Java", 2nd
35   * edition, item 71. The class already implements all necessary synchronization.
36   * A concrete subclass has to implement the {@code initialize()} method, which
37   * actually creates the wrapped data object.
38   * </p>
39   * <p>
40   * As an usage example consider that we have a class {@code ComplexObject} whose
41   * instantiation is a complex operation. In order to apply lazy initialization
42   * to this class, a subclass of {@code LazyInitializer} has to be created:
43   *
44   * <pre>
45   * public class ComplexObjectInitializer extends LazyInitializer&lt;ComplexObject&gt; {
46   *     &#064;Override
47   *     protected ComplexObject initialize() {
48   *         return new ComplexObject();
49   *     }
50   * }
51   * </pre>
52   *
53   * Access to the data object is provided through the {@code get()} method. So,
54   * code that wants to obtain the {@code ComplexObject} instance would simply
55   * look like this:
56   *
57   * <pre>
58   * // Create an instance of the lazy initializer
59   * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
60   * ...
61   * // When the object is actually needed:
62   * ComplexObject cobj = initializer.get();
63   * </pre>
64   *
65   * </p>
66   * <p>
67   * If multiple threads call the {@code get()} method when the object has not yet
68   * been created, they are blocked until initialization completes. The algorithm
69   * guarantees that only a single instance of the wrapped object class is
70   * created, which is passed to all callers. Once initialized, calls to the
71   * {@code get()} method are pretty fast because no synchronization is needed
72   * (only an access to a <b>volatile</b> member field).
73   * </p>
74   *
75   * @since 3.0
76   * @version $Id: LazyInitializer.java 1309977 2012-04-05 17:53:39Z ggregory $
77   * @param <T> the type of the object managed by this initializer class
78   */
79  public abstract class LazyInitializer<T> implements ConcurrentInitializer<T> {
80      /** Stores the managed object. */
81      private volatile T object;
82  
83      /**
84       * Returns the object wrapped by this instance. On first access the object
85       * is created. After that it is cached and can be accessed pretty fast.
86       *
87       * @return the object initialized by this {@code LazyInitializer}
88       * @throws ConcurrentException if an error occurred during initialization of
89       * the object
90       */
91      @Override
92      public T get() throws ConcurrentException {
93          // use a temporary variable to reduce the number of reads of the
94          // volatile field
95          T result = object;
96  
97          if (result == null) {
98              synchronized (this) {
99                  result = object;
100                 if (result == null) {
101                     object = result = initialize();
102                 }
103             }
104         }
105 
106         return result;
107     }
108 
109     /**
110      * Creates and initializes the object managed by this {@code
111      * LazyInitializer}. This method is called by {@link #get()} when the object
112      * is accessed for the first time. An implementation can focus on the
113      * creation of the object. No synchronization is needed, as this is already
114      * handled by {@code get()}.
115      *
116      * @return the managed data object
117      * @throws ConcurrentException if an error occurs during object creation
118      */
119     protected abstract T initialize() throws ConcurrentException;
120 }