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
019import org.apache.commons.lang3.function.FailableConsumer;
020import org.apache.commons.lang3.function.FailableSupplier;
021
022/**
023 * This class provides a generic implementation of the lazy initialization pattern.
024 *
025 * <p>
026 * Sometimes an application has to deal with an object only under certain circumstances, e.g. when the user selects a specific menu item or if a special event
027 * is received. If the creation of the object is costly or the consumption of memory or other system resources is significant, it may make sense to defer the
028 * creation of this object until it is really needed. This is a use case for the lazy initialization pattern.
029 * </p>
030 * <p>
031 * This abstract base class provides an implementation of the double-check idiom for an instance field as discussed in Joshua Bloch's "Effective Java", 2nd
032 * edition, item 71. The class already implements all necessary synchronization. A concrete subclass has to implement the {@code initialize()} method, which
033 * actually creates the wrapped data object.
034 * </p>
035 * <p>
036 * As an usage example consider that we have a class {@code ComplexObject} whose instantiation is a complex operation. In order to apply lazy initialization to
037 * this class, a subclass of {@link LazyInitializer} has to be created:
038 * </p>
039 *
040 * <pre>
041 * public class ComplexObjectInitializer extends LazyInitializer&lt;ComplexObject&gt; {
042 *     &#064;Override
043 *     protected ComplexObject initialize() {
044 *         return new ComplexObject();
045 *     }
046 * }
047 * </pre>
048 *
049 * <p>
050 * Access to the data object is provided through the {@code get()} method. So, code that wants to obtain the {@code ComplexObject} instance would simply look
051 * like this:
052 * </p>
053 *
054 * <pre>
055 * // Create an instance of the lazy initializer
056 * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
057 * ...
058 * // When the object is actually needed:
059 * ComplexObject cobj = initializer.get();
060 * </pre>
061 *
062 * <p>
063 * If multiple threads call the {@code get()} method when the object has not yet been created, they are blocked until initialization completes. The algorithm
064 * guarantees that only a single instance of the wrapped object class is created, which is passed to all callers. Once initialized, calls to the {@code get()}
065 * method are pretty fast because no synchronization is needed (only an access to a <b>volatile</b> member field).
066 * </p>
067 *
068 * @since 3.0
069 * @param <T> the type of the object managed by the initializer.
070 */
071public class LazyInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {
072
073    /**
074     * Builds a new instance.
075     *
076     * @param <T> the type of the object managed by the initializer.
077     * @param <I> the type of the initializer managed by this builder.
078     * @since 3.14.0
079     */
080    public static class Builder<I extends LazyInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> {
081
082        @SuppressWarnings("unchecked")
083        @Override
084        public I get() {
085            return (I) new LazyInitializer(getInitializer(), getCloser());
086        }
087
088    }
089
090    /**
091     * A unique value indicating an un-initialzed instance.
092     */
093    private static final Object NO_INIT = new Object();
094
095    /**
096     * Creates a new builder.
097     *
098     * @param <T> the type of object to build.
099     * @return a new builder.
100     * @since 3.14.0
101     */
102    public static <T> Builder<LazyInitializer<T>, T> builder() {
103        return new Builder<>();
104    }
105
106    /** Stores the managed object. */
107    @SuppressWarnings("unchecked")
108    private volatile T object = (T) NO_INIT;
109
110    /**
111     * Constructs a new instance.
112     */
113    public LazyInitializer() {
114        // empty
115    }
116
117    /**
118     * Constructs a new instance.
119     *
120     * @param initializer the initializer supplier called by {@link #initialize()}.
121     * @param closer the closer consumer called by {@link #close()}.
122     */
123    private LazyInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
124        super(initializer, closer);
125    }
126
127    /**
128     * 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.
129     *
130     * @return the object initialized by this {@link LazyInitializer}
131     * @throws ConcurrentException if an error occurred during initialization of the object
132     */
133    @Override
134    public T get() throws ConcurrentException {
135        // use a temporary variable to reduce the number of reads of the
136        // volatile field
137        T result = object;
138
139        if (result == NO_INIT) {
140            synchronized (this) {
141                result = object;
142                if (result == NO_INIT) {
143                    object = result = initialize();
144                }
145            }
146        }
147
148        return result;
149    }
150
151    /**
152     * {@inheritDoc}
153     */
154    @Override
155    protected ConcurrentException getTypedException(Exception e) {
156        return new ConcurrentException(e);
157    }
158
159    /**
160     * Tests whether this instance is initialized. Once initialized, always returns true.
161     *
162     * @return whether this instance is initialized. Once initialized, always returns true.
163     * @since 3.14.0
164     */
165    @Override
166    public boolean isInitialized() {
167        return object != NO_INIT;
168    }
169
170}