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>{@code
041 * public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> {
042 *     &#064;Override
043 *     protected ComplexObject initialize() {
044 *         return new ComplexObject();
045 *     }
046 * }
047 * }
048 * </pre>
049 *
050 * <p>
051 * 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
052 * like this:
053 * </p>
054 *
055 * <pre>
056 * // Create an instance of the lazy initializer
057 * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
058 * ...
059 * // When the object is actually needed:
060 * ComplexObject cobj = initializer.get();
061 * </pre>
062 *
063 * <p>
064 * If multiple threads call the {@code get()} method when the object has not yet been created, they are blocked until initialization completes. The algorithm
065 * 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()}
066 * method are pretty fast because no synchronization is needed (only an access to a <b>volatile</b> member field).
067 * </p>
068 *
069 * @since 3.0
070 * @param <T> the type of the object managed by the initializer.
071 */
072public class LazyInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {
073
074    /**
075     * Builds a new instance.
076     *
077     * @param <T> the type of the object managed by the initializer.
078     * @param <I> the type of the initializer managed by this builder.
079     * @since 3.14.0
080     */
081    public static class Builder<I extends LazyInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> {
082
083        /**
084         * Constructs a new instance.
085         */
086        public Builder() {
087            // empty
088        }
089
090        @SuppressWarnings("unchecked")
091        @Override
092        public I get() {
093            return (I) new LazyInitializer(getInitializer(), getCloser());
094        }
095
096    }
097
098    /**
099     * A unique value indicating an un-initialized instance.
100     */
101    private static final Object NO_INIT = new Object();
102
103    /**
104     * Creates a new builder.
105     *
106     * @param <T> the type of object to build.
107     * @return a new builder.
108     * @since 3.14.0
109     */
110    public static <T> Builder<LazyInitializer<T>, T> builder() {
111        return new Builder<>();
112    }
113
114    /** Stores the managed object. */
115    @SuppressWarnings("unchecked")
116    private volatile T object = (T) NO_INIT;
117
118    /**
119     * Constructs a new instance.
120     */
121    public LazyInitializer() {
122        // empty
123    }
124
125    /**
126     * Constructs a new instance.
127     *
128     * @param initializer the initializer supplier called by {@link #initialize()}.
129     * @param closer the closer consumer called by {@link #close()}.
130     */
131    private LazyInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
132        super(initializer, closer);
133    }
134
135    /**
136     * 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.
137     *
138     * @return the object initialized by this {@link LazyInitializer}
139     * @throws ConcurrentException if an error occurred during initialization of the object
140     */
141    @Override
142    public T get() throws ConcurrentException {
143        // use a temporary variable to reduce the number of reads of the
144        // volatile field
145        T result = object;
146
147        if (result == NO_INIT) {
148            synchronized (this) {
149                result = object;
150                if (result == NO_INIT) {
151                    object = result = initialize();
152                }
153            }
154        }
155
156        return result;
157    }
158
159    /**
160     * {@inheritDoc}
161     */
162    @Override
163    protected ConcurrentException getTypedException(final Exception e) {
164        return new ConcurrentException(e);
165    }
166
167    /**
168     * Tests whether this instance is initialized. Once initialized, always returns true.
169     *
170     * @return whether this instance is initialized. Once initialized, always returns true.
171     * @since 3.14.0
172     */
173    @Override
174    public boolean isInitialized() {
175        return object != NO_INIT;
176    }
177
178}