    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3.concurrent;
    018
    019/**
    020 * This class provides a generic implementation of the lazy initialization
    021 * pattern.
    022 *
    023 * <p>
    024 * Sometimes an application has to deal with an object only under certain
    025 * circumstances, e.g. when the user selects a specific menu item or if a
    026 * special event is received. If the creation of the object is costly or the
    027 * consumption of memory or other system resources is significant, it may make
    028 * sense to defer the creation of this object until it is really needed. This is
    029 * a use case for the lazy initialization pattern.
    030 * </p>
    031 * <p>
    032 * This abstract base class provides an implementation of the double-check idiom
    033 * for an instance field as discussed in Joshua Bloch's "Effective Java", 2nd
    034 * edition, item 71. The class already implements all necessary synchronization.
    035 * A concrete subclass has to implement the {@code initialize()} method, which
    036 * actually creates the wrapped data object.
    037 * </p>
    038 * <p>
    039 * As an usage example consider that we have a class {@code ComplexObject} whose
    040 * instantiation is a complex operation. In order to apply lazy initialization
    041 * to this class, a subclass of {@link LazyInitializer} has to be created:
    042 * </p>
    043 *
    044 * <pre>
    045 * public class ComplexObjectInitializer extends LazyInitializer&lt;ComplexObject&gt; {
    046 *     &#064;Override
    047 *     protected ComplexObject initialize() {
    048 *         return new ComplexObject();
    049 *     }
    050 * }
    051 * </pre>
    052 *
    053 * <p>
    054 * Access to the data object is provided through the {@code get()} method. So,
    055 * code that wants to obtain the {@code ComplexObject} instance would simply
    056 * look like this:
    057 * </p>
    058 *
    059 * <pre>
    060 * // Create an instance of the lazy initializer
    061 * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
    062 * ...
    063 * // When the object is actually needed:
    064 * ComplexObject cobj = initializer.get();
    065 * </pre>
    066 *
    067 * <p>
    068 * If multiple threads call the {@code get()} method when the object has not yet
    069 * been created, they are blocked until initialization completes. The algorithm
    070 * guarantees that only a single instance of the wrapped object class is
    071 * created, which is passed to all callers. Once initialized, calls to the
    072 * {@code get()} method are pretty fast because no synchronization is needed
    073 * (only an access to a <b>volatile</b> member field).
    074 * </p>
    075 *
    076 * @since 3.0
    077 * @param <T> the type of the object managed by this initializer class
    078 */
    079public abstract class LazyInitializer<T> implements ConcurrentInitializer<T> {
    080
    081    private static final Object NO_INIT = new Object();
    082
    083    @SuppressWarnings("unchecked")
    084    // Stores the managed object.
    085    private volatile T object = (T) NO_INIT;
    086
    087    /**
    088     * Returns the object wrapped by this instance. On first access the object
    089     * is created. After that it is cached and can be accessed pretty fast.
    090     *
    091     * @return the object initialized by this {@link LazyInitializer}
    092     * @throws ConcurrentException if an error occurred during initialization of
    093     * the object
    094     */
    095    @Override
    096    public T get() throws ConcurrentException {
    097        // use a temporary variable to reduce the number of reads of the
    098        // volatile field
    099        T result = object;
    100
    101        if (result == NO_INIT) {
    102            synchronized (this) {
    103                result = object;
    104                if (result == NO_INIT) {
    105                    object = result = initialize();
    106                }
    107            }
    108        }
    109
    110        return result;
    111    }
    112
    113    /**
    114     * Creates and initializes the object managed by this {@code
    115     * LazyInitializer}. This method is called by {@link #get()} when the object
    116     * is accessed for the first time. An implementation can focus on the
    117     * creation of the object. No synchronization is needed, as this is already
    118     * handled by {@code get()}.
    119     *
    120     * @return the managed data object
    121     * @throws ConcurrentException if an error occurs during object creation
    122     */
    123    protected abstract T initialize() throws ConcurrentException;
    124}