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   * </p>
44   *
45   * <pre>
46   * public class ComplexObjectInitializer extends LazyInitializer&lt;ComplexObject&gt; {
47   *     &#064;Override
48   *     protected ComplexObject initialize() {
49   *         return new ComplexObject();
50   *     }
51   * }
52   * </pre>
53   *
54   * <p>
55   * Access to the data object is provided through the {@code get()} method. So,
56   * code that wants to obtain the {@code ComplexObject} instance would simply
57   * look like this:
58   * </p>
59   *
60   * <pre>
61   * // Create an instance of the lazy initializer
62   * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
63   * ...
64   * // When the object is actually needed:
65   * ComplexObject cobj = initializer.get();
66   * </pre>
67   *
68   * <p>
69   * If multiple threads call the {@code get()} method when the object has not yet
70   * been created, they are blocked until initialization completes. The algorithm
71   * guarantees that only a single instance of the wrapped object class is
72   * created, which is passed to all callers. Once initialized, calls to the
73   * {@code get()} method are pretty fast because no synchronization is needed
74   * (only an access to a <b>volatile</b> member field).
75   * </p>
76   *
77   * @since 3.0
78   * @param <T> the type of the object managed by this initializer class
79   */
80  public abstract class LazyInitializer<T> implements ConcurrentInitializer<T> {
81      /** Stores the managed object. */
82      private volatile T object;
83  
84      /**
85       * Returns the object wrapped by this instance. On first access the object
86       * is created. After that it is cached and can be accessed pretty fast.
87       *
88       * @return the object initialized by this {@code LazyInitializer}
89       * @throws ConcurrentException if an error occurred during initialization of
90       * the object
91       */
92      @Override
93      public T get() throws ConcurrentException {
94          // use a temporary variable to reduce the number of reads of the
95          // volatile field
96          T result = object;
97  
98          if (result == null) {
99              synchronized (this) {
100                 result = object;
101                 if (result == null) {
102                     object = result = initialize();
103                 }
104             }
105         }
106 
107         return result;
108     }
109 
110     /**
111      * Creates and initializes the object managed by this {@code
112      * LazyInitializer}. This method is called by {@link #get()} when the object
113      * is accessed for the first time. An implementation can focus on the
114      * creation of the object. No synchronization is needed, as this is already
115      * handled by {@code get()}.
116      *
117      * @return the managed data object
118      * @throws ConcurrentException if an error occurs during object creation
119      */
120     protected abstract T initialize() throws ConcurrentException;
121 }