AtomicInitializer.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3.concurrent;

  18. import java.util.concurrent.atomic.AtomicReference;

  19. import org.apache.commons.lang3.function.FailableConsumer;
  20. import org.apache.commons.lang3.function.FailableSupplier;

  21. /**
  22.  * A specialized implementation of the {@link ConcurrentInitializer} interface
  23.  * based on an {@link AtomicReference} variable.
  24.  *
  25.  * <p>
  26.  * This class maintains a member field of type {@link AtomicReference}. It
  27.  * implements the following algorithm to create and initialize an object in its
  28.  * {@link #get()} method:
  29.  * </p>
  30.  * <ul>
  31.  * <li>First it is checked whether the {@link AtomicReference} variable contains
  32.  * already a value. If this is the case, the value is directly returned.</li>
  33.  * <li>Otherwise the {@link #initialize()} method is called. This method must be
  34.  * defined in concrete subclasses to actually create the managed object.</li>
  35.  * <li>After the object was created by {@link #initialize()} it is checked
  36.  * whether the {@link AtomicReference} variable is still undefined. This has to
  37.  * be done because in the meantime another thread may have initialized the
  38.  * object. If the reference is still empty, the newly created object is stored
  39.  * in it and returned by this method.</li>
  40.  * <li>Otherwise the value stored in the {@link AtomicReference} is returned.</li>
  41.  * </ul>
  42.  * <p>
  43.  * Because atomic variables are used this class does not need any
  44.  * synchronization. So there is no danger of deadlock, and access to the managed
  45.  * object is efficient. However, if multiple threads access the {@code
  46.  * AtomicInitializer} object before it has been initialized almost at the same
  47.  * time, it can happen that {@link #initialize()} is called multiple times. The
  48.  * algorithm outlined above guarantees that {@link #get()} always returns the
  49.  * same object though.
  50.  * </p>
  51.  * <p>
  52.  * Compared with the {@link LazyInitializer} class, this class can be more
  53.  * efficient because it does not need synchronization. The drawback is that the
  54.  * {@link #initialize()} method can be called multiple times which may be
  55.  * problematic if the creation of the managed object is expensive. As a rule of
  56.  * thumb this initializer implementation is preferable if there are not too many
  57.  * threads involved and the probability that multiple threads access an
  58.  * uninitialized object is small. If there is high parallelism,
  59.  * {@link LazyInitializer} is more appropriate.
  60.  * </p>
  61.  *
  62.  * @since 3.0
  63.  * @param <T> the type of the object managed by this initializer class
  64.  */
  65. public class AtomicInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> {

  66.     /**
  67.      * Builds a new instance.
  68.      *
  69.      * @param <T> the type of the object managed by the initializer.
  70.      * @param <I> the type of the initializer managed by this builder.
  71.      * @since 3.14.0
  72.      */
  73.     public static class Builder<I extends AtomicInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> {

  74.         /**
  75.          * Constructs a new instance.
  76.          */
  77.         public Builder() {
  78.             // empty
  79.         }

  80.         @SuppressWarnings("unchecked")
  81.         @Override
  82.         public I get() {
  83.             return (I) new AtomicInitializer(getInitializer(), getCloser());
  84.         }

  85.     }

  86.     private static final Object NO_INIT = new Object();

  87.     /**
  88.      * Creates a new builder.
  89.      *
  90.      * @param <T> the type of object to build.
  91.      * @return a new builder.
  92.      * @since 3.14.0
  93.      */
  94.     public static <T> Builder<AtomicInitializer<T>, T> builder() {
  95.         return new Builder<>();
  96.     }

  97.     /** Holds the reference to the managed object. */
  98.     private final AtomicReference<T> reference = new AtomicReference<>(getNoInit());

  99.     /**
  100.      * Constructs a new instance.
  101.      */
  102.     public AtomicInitializer() {
  103.         // empty
  104.     }

  105.     /**
  106.      * Constructs a new instance.
  107.      *
  108.      * @param initializer the initializer supplier called by {@link #initialize()}.
  109.      * @param closer the closer consumer called by {@link #close()}.
  110.      */
  111.     private AtomicInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) {
  112.         super(initializer, closer);
  113.     }

  114.     /**
  115.      * Returns the object managed by this initializer. The object is created if
  116.      * it is not available yet and stored internally. This method always returns
  117.      * the same object.
  118.      *
  119.      * @return the object created by this {@link AtomicInitializer}
  120.      * @throws ConcurrentException if an error occurred during initialization of
  121.      * the object
  122.      */
  123.     @Override
  124.     public T get() throws ConcurrentException {
  125.         T result = reference.get();

  126.         if (result == getNoInit()) {
  127.             result = initialize();
  128.             if (!reference.compareAndSet(getNoInit(), result)) {
  129.                 // another thread has initialized the reference
  130.                 result = reference.get();
  131.             }
  132.         }

  133.         return result;
  134.     }

  135.     /** Gets the internal no-init object cast for this instance. */
  136.     @SuppressWarnings("unchecked")
  137.     private T getNoInit() {
  138.         return (T) NO_INIT;
  139.     }

  140.     /**
  141.      * {@inheritDoc}
  142.      */
  143.     @Override
  144.     protected ConcurrentException getTypedException(final Exception e) {
  145.         return new ConcurrentException(e);
  146.     }

  147.     /**
  148.      * Tests whether this instance is initialized. Once initialized, always returns true.
  149.      *
  150.      * @return whether this instance is initialized. Once initialized, always returns true.
  151.      * @since 3.14.0
  152.      */
  153.     @Override
  154.     public boolean isInitialized() {
  155.         return reference.get() != NO_INIT;
  156.     }
  157. }