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 19 import java.util.concurrent.atomic.AtomicReference; 20 21 import org.apache.commons.lang3.function.FailableConsumer; 22 import org.apache.commons.lang3.function.FailableSupplier; 23 24 /** 25 * A specialized implementation of the {@link ConcurrentInitializer} interface 26 * based on an {@link AtomicReference} variable. 27 * 28 * <p> 29 * This class maintains a member field of type {@link AtomicReference}. It 30 * implements the following algorithm to create and initialize an object in its 31 * {@link #get()} method: 32 * </p> 33 * <ul> 34 * <li>First it is checked whether the {@link AtomicReference} variable contains 35 * already a value. If this is the case, the value is directly returned.</li> 36 * <li>Otherwise the {@link #initialize()} method is called. This method must be 37 * defined in concrete subclasses to actually create the managed object.</li> 38 * <li>After the object was created by {@link #initialize()} it is checked 39 * whether the {@link AtomicReference} variable is still undefined. This has to 40 * be done because in the meantime another thread may have initialized the 41 * object. If the reference is still empty, the newly created object is stored 42 * in it and returned by this method.</li> 43 * <li>Otherwise the value stored in the {@link AtomicReference} is returned.</li> 44 * </ul> 45 * <p> 46 * Because atomic variables are used this class does not need any 47 * synchronization. So there is no danger of deadlock, and access to the managed 48 * object is efficient. However, if multiple threads access the {@code 49 * AtomicInitializer} object before it has been initialized almost at the same 50 * time, it can happen that {@link #initialize()} is called multiple times. The 51 * algorithm outlined above guarantees that {@link #get()} always returns the 52 * same object though. 53 * </p> 54 * <p> 55 * Compared with the {@link LazyInitializer} class, this class can be more 56 * efficient because it does not need synchronization. The drawback is that the 57 * {@link #initialize()} method can be called multiple times which may be 58 * problematic if the creation of the managed object is expensive. As a rule of 59 * thumb this initializer implementation is preferable if there are not too many 60 * threads involved and the probability that multiple threads access an 61 * uninitialized object is small. If there is high parallelism, 62 * {@link LazyInitializer} is more appropriate. 63 * </p> 64 * 65 * @since 3.0 66 * @param <T> the type of the object managed by this initializer class 67 */ 68 public class AtomicInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> { 69 70 /** 71 * Builds a new instance. 72 * 73 * @param <T> the type of the object managed by the initializer. 74 * @param <I> the type of the initializer managed by this builder. 75 * @since 3.14.0 76 */ 77 public static class Builder<I extends AtomicInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> { 78 79 @SuppressWarnings("unchecked") 80 @Override 81 public I get() { 82 return (I) new AtomicInitializer(getInitializer(), getCloser()); 83 } 84 85 } 86 87 private static final Object NO_INIT = new Object(); 88 89 /** 90 * Creates a new builder. 91 * 92 * @param <T> the type of object to build. 93 * @return a new builder. 94 * @since 3.14.0 95 */ 96 public static <T> Builder<AtomicInitializer<T>, T> builder() { 97 return new Builder<>(); 98 } 99 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(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 }