    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 {@link ConcurrentInitializer} implementation which is similar
    026 * to {@link AtomicInitializer}, but ensures that the {@link #initialize()}
    027 * method is called only once.
    028 *
    029 * <p>
    030 * As {@link AtomicInitializer} this class is based on atomic variables, so it
    031 * can create an object under concurrent access without synchronization.
    032 * However, it implements an additional check to guarantee that the
    033 * {@link #initialize()} method which actually creates the object cannot be
    034 * called multiple times.
    035 * </p>
    036 * <p>
    037 * Because of this additional check this implementation is slightly less
    038 * efficient than {@link AtomicInitializer}, but if the object creation in the
    039 * {@code initialize()} method is expensive or if multiple invocations of
    040 * {@code initialize()} are problematic, it is the better alternative.
    041 * </p>
    042 * <p>
    043 * From its semantics this class has the same properties as
    044 * {@link LazyInitializer}. It is a &quot;save&quot; implementation of the lazy
    045 * initializer pattern. Comparing both classes in terms of efficiency is
    046 * difficult because which one is faster depends on multiple factors. Because
    047 * {@link AtomicSafeInitializer} does not use synchronization at all it probably
    048 * outruns {@link LazyInitializer}, at least under low or moderate concurrent
    049 * access. Developers should run their own benchmarks on the expected target
    050 * platform to decide which implementation is suitable for their specific use
    051 * case.
    052 * </p>
    053 *
    054 * @since 3.0
    055 * @param <T> the type of the object managed by this initializer class
    056 */
    057public class AtomicSafeInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {
    058
    059    /**
    060     * Builds a new instance.
    061     *
    062     * @param <T> the type of the object managed by the initializer.
    063     * @param <I> the type of the initializer managed by this builder.
    064     * @since 3.14.0
    065     */
    066    public static class Builder<I extends AtomicSafeInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> {
    067
    068        @SuppressWarnings("unchecked")
    069        @Override
    070        public I get() {
    071            return (I) new AtomicSafeInitializer(getInitializer(), getCloser());
    072        }
    073
    074    }
    075
    076    private static final Object NO_INIT = new Object();
    077
    078    /**
    079     * Creates a new builder.
    080     *
    081     * @param <T> the type of object to build.
    082     * @return a new builder.
    083     * @since 3.14.0
    084     */
    085    public static <T> Builder<AtomicSafeInitializer<T>, T> builder() {
    086        return new Builder<>();
    087    }
    088
    089    /** A guard which ensures that initialize() is called only once. */
    090    private final AtomicReference<AtomicSafeInitializer<T>> factory = new AtomicReference<>();
    091
    092    /** Holds the reference to the managed object. */
    093    private final AtomicReference<T> reference = new AtomicReference<>(getNoInit());
    094
    095    /**
    096     * Constructs a new instance.
    097     */
    098    public AtomicSafeInitializer() {
    099        // empty
    100    }
    101
    102    /**
    103     * Constructs a new instance.
    104     *
    105     * @param initializer the initializer supplier called by {@link #initialize()}.
    106     * @param closer the closer consumer called by {@link #close()}.
    107     */
    108    private AtomicSafeInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
    109        super(initializer, closer);
    110    }
    111
    112    /**
    113     * Gets (and initialize, if not initialized yet) the required object
    114     *
    115     * @return lazily initialized object
    116     * @throws ConcurrentException if the initialization of the object causes an
    117     * exception
    118     */
    119    @Override
    120    public final T get() throws ConcurrentException {
    121        T result;
    122
    123        while ((result = reference.get()) == getNoInit()) {
    124            if (factory.compareAndSet(null, this)) {
    125                reference.set(initialize());
    126            }
    127        }
    128
    129        return result;
    130    }
    131
    132    /** Gets the internal no-init object cast for this instance. */
    133    @SuppressWarnings("unchecked")
    134    private T getNoInit() {
    135        return (T) NO_INIT;
    136    }
    137
    138    /**
    139     * {@inheritDoc}
    140     */
    141    @Override
    142    protected ConcurrentException getTypedException(final Exception e) {
    143        return new ConcurrentException(e);
    144    }
    145
    146    /**
    147     * Tests whether this instance is initialized. Once initialized, always returns true.
    148     *
    149     * @return whether this instance is initialized. Once initialized, always returns true.
    150     * @since 3.14.0
    151     */
    152    @Override
    153    public boolean isInitialized() {
    154        return reference.get() != NO_INIT;
    155    }
    156}