    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 *      https://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 * @param <T> the type of the object managed by this initializer class.
    066 * @since 3.0
    067 */
    068public class AtomicInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {
    069
    070    /**
    071     * Builds a new instance.
    072     *
    073     * @param <T> The type of results supplied by this builder.
    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     * Gets the object managed by this initializer. The object is created if it is not available yet and stored internally. This method always returns the same
    129     * object.
    130     *
    131     * @return the object created by this {@link AtomicInitializer}.
    132     * @throws ConcurrentException if an error occurred during initialization of the object.
    133     */
    134    @Override
    135    public T get() throws ConcurrentException {
    136        T result = reference.get();
    137        if (result == getNoInit()) {
    138            result = initialize();
    139            if (!reference.compareAndSet(getNoInit(), result)) {
    140                // another thread has initialized the reference
    141                result = reference.get();
    142            }
    143        }
    144        return result;
    145    }
    146
    147    /** Gets the internal no-init object cast for this instance. */
    148    @SuppressWarnings("unchecked")
    149    private T getNoInit() {
    150        return (T) NO_INIT;
    151    }
    152
    153    /**
    154     * {@inheritDoc}
    155     */
    156    @Override
    157    protected ConcurrentException getTypedException(final Exception e) {
    158        return new ConcurrentException(e);
    159    }
    160
    161    /**
    162     * Tests whether this instance is initialized. Once initialized, always returns true.
    163     *
    164     * @return whether this instance is initialized. Once initialized, always returns true.
    165     * @since 3.14.0
    166     */
    167    @Override
    168    public boolean isInitialized() {
    169        return reference.get() != NO_INIT;
    170    }
    171}