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 java.util.concurrent.atomic.AtomicReference;
020
021import org.apache.commons.lang3.function.FailableConsumer;
022import org.apache.commons.lang3.function.FailableSupplier;
023
024/**
025 * A specialized implementation of the {@link ConcurrentInitializer} interface
026 * based on an {@link AtomicReference} variable.
027 *
028 * <p>
029 * This class maintains a member field of type {@link AtomicReference}. It
030 * implements the following algorithm to create and initialize an object in its
031 * {@link #get()} method:
032 * </p>
033 * <ul>
034 * <li>First it is checked whether the {@link AtomicReference} variable contains
035 * already a value. If this is the case, the value is directly returned.</li>
036 * <li>Otherwise the {@link #initialize()} method is called. This method must be
037 * defined in concrete subclasses to actually create the managed object.</li>
038 * <li>After the object was created by {@link #initialize()} it is checked
039 * whether the {@link AtomicReference} variable is still undefined. This has to
040 * be done because in the meantime another thread may have initialized the
041 * object. If the reference is still empty, the newly created object is stored
042 * in it and returned by this method.</li>
043 * <li>Otherwise the value stored in the {@link AtomicReference} is returned.</li>
044 * </ul>
045 * <p>
046 * Because atomic variables are used this class does not need any
047 * synchronization. So there is no danger of deadlock, and access to the managed
048 * object is efficient. However, if multiple threads access the {@code
049 * AtomicInitializer} object before it has been initialized almost at the same
050 * time, it can happen that {@link #initialize()} is called multiple times. The
051 * algorithm outlined above guarantees that {@link #get()} always returns the
052 * same object though.
053 * </p>
054 * <p>
055 * Compared with the {@link LazyInitializer} class, this class can be more
056 * efficient because it does not need synchronization. The drawback is that the
057 * {@link #initialize()} method can be called multiple times which may be
058 * problematic if the creation of the managed object is expensive. As a rule of
059 * thumb this initializer implementation is preferable if there are not too many
060 * threads involved and the probability that multiple threads access an
061 * uninitialized object is small. If there is high parallelism,
062 * {@link LazyInitializer} is more appropriate.
063 * </p>
064 *
065 * @since 3.0
066 * @param <T> the type of the object managed by this initializer class
067 */
068public class AtomicInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {
069
070    /**
071     * Builds a new instance.
072     *
073     * @param <T> the type of the object managed by the initializer.
074     * @param <I> the type of the initializer managed by this builder.
075     * @since 3.14.0
076     */
077    public static class Builder<I extends AtomicInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> {
078
079        /**
080         * Constructs a new instance.
081         */
082        public Builder() {
083            // empty
084        }
085
086        @SuppressWarnings("unchecked")
087        @Override
088        public I get() {
089            return (I) new AtomicInitializer(getInitializer(), getCloser());
090        }
091
092    }
093
094    private static final Object NO_INIT = new Object();
095
096    /**
097     * Creates a new builder.
098     *
099     * @param <T> the type of object to build.
100     * @return a new builder.
101     * @since 3.14.0
102     */
103    public static <T> Builder<AtomicInitializer<T>, T> builder() {
104        return new Builder<>();
105    }
106
107    /** Holds the reference to the managed object. */
108    private final AtomicReference<T> reference = new AtomicReference<>(getNoInit());
109
110    /**
111     * Constructs a new instance.
112     */
113    public AtomicInitializer() {
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 AtomicInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
124        super(initializer, closer);
125    }
126
127    /**
128     * Returns the object managed by this initializer. The object is created if
129     * it is not available yet and stored internally. This method always returns
130     * the same object.
131     *
132     * @return the object created by this {@link AtomicInitializer}
133     * @throws ConcurrentException if an error occurred during initialization of
134     * the object
135     */
136    @Override
137    public T get() throws ConcurrentException {
138        T result = reference.get();
139
140        if (result == getNoInit()) {
141            result = initialize();
142            if (!reference.compareAndSet(getNoInit(), result)) {
143                // another thread has initialized the reference
144                result = reference.get();
145            }
146        }
147
148        return result;
149    }
150
151    /** Gets the internal no-init object cast for this instance. */
152    @SuppressWarnings("unchecked")
153    private T getNoInit() {
154        return (T) NO_INIT;
155    }
156
157    /**
158     * {@inheritDoc}
159     */
160    @Override
161    protected ConcurrentException getTypedException(final Exception e) {
162        return new ConcurrentException(e);
163    }
164
165    /**
166     * Tests whether this instance is initialized. Once initialized, always returns true.
167     *
168     * @return whether this instance is initialized. Once initialized, always returns true.
169     * @since 3.14.0
170     */
171    @Override
172    public boolean isInitialized() {
173        return reference.get() != NO_INIT;
174    }
175}