    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        @SuppressWarnings("unchecked")
    080        @Override
    081        public I get() {
    082            return (I) new AtomicInitializer(getInitializer(), getCloser());
    083        }
    084
    085    }
    086
    087    private static final Object NO_INIT = new Object();
    088
    089    /**
    090     * Creates a new builder.
    091     *
    092     * @param <T> the type of object to build.
    093     * @return a new builder.
    094     * @since 3.14.0
    095     */
    096    public static <T> Builder<AtomicInitializer<T>, T> builder() {
    097        return new Builder<>();
    098    }
    099
    100    /** Holds the reference to the managed object. */
    101    private final AtomicReference<T> reference = new AtomicReference<>(getNoInit());
    102
    103    /**
    104     * Constructs a new instance.
    105     */
    106    public AtomicInitializer() {
    107        // empty
    108    }
    109
    110    /**
    111     * Constructs a new instance.
    112     *
    113     * @param initializer the initializer supplier called by {@link #initialize()}.
    114     * @param closer the closer consumer called by {@link #close()}.
    115     */
    116    private AtomicInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
    117        super(initializer, closer);
    118    }
    119
    120    /**
    121     * Returns the object managed by this initializer. The object is created if
    122     * it is not available yet and stored internally. This method always returns
    123     * the same object.
    124     *
    125     * @return the object created by this {@link AtomicInitializer}
    126     * @throws ConcurrentException if an error occurred during initialization of
    127     * the object
    128     */
    129    @Override
    130    public T get() throws ConcurrentException {
    131        T result = reference.get();
    132
    133        if (result == getNoInit()) {
    134            result = initialize();
    135            if (!reference.compareAndSet(getNoInit(), result)) {
    136                // another thread has initialized the reference
    137                result = reference.get();
    138            }
    139        }
    140
    141        return result;
    142    }
    143
    144    /** Gets the internal no-init object cast for this instance. */
    145    @SuppressWarnings("unchecked")
    146    private T getNoInit() {
    147        return (T) NO_INIT;
    148    }
    149
    150    /**
    151     * {@inheritDoc}
    152     */
    153    @Override
    154    protected ConcurrentException getTypedException(final Exception e) {
    155        return new ConcurrentException(e);
    156    }
    157
    158    /**
    159     * Tests whether this instance is initialized. Once initialized, always returns true.
    160     *
    161     * @return whether this instance is initialized. Once initialized, always returns true.
    162     * @since 3.14.0
    163     */
    164    @Override
    165    public boolean isInitialized() {
    166        return reference.get() != NO_INIT;
    167    }
    168}