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 org.apache.commons.lang3.function.FailableConsumer; 20 import org.apache.commons.lang3.function.FailableSupplier; 21 22 /** 23 * This class provides a generic implementation of the lazy initialization pattern. 24 * 25 * <p> 26 * Sometimes an application has to deal with an object only under certain circumstances, e.g. when the user selects a specific menu item or if a special event 27 * is received. If the creation of the object is costly or the consumption of memory or other system resources is significant, it may make sense to defer the 28 * creation of this object until it is really needed. This is a use case for the lazy initialization pattern. 29 * </p> 30 * <p> 31 * This abstract base class provides an implementation of the double-check idiom for an instance field as discussed in Joshua Bloch's "Effective Java", 2nd 32 * edition, item 71. The class already implements all necessary synchronization. A concrete subclass has to implement the {@code initialize()} method, which 33 * actually creates the wrapped data object. 34 * </p> 35 * <p> 36 * As an usage example consider that we have a class {@code ComplexObject} whose instantiation is a complex operation. In order to apply lazy initialization to 37 * this class, a subclass of {@link LazyInitializer} has to be created: 38 * </p> 39 * 40 * <pre> 41 * public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> { 42 * @Override 43 * protected ComplexObject initialize() { 44 * return new ComplexObject(); 45 * } 46 * } 47 * </pre> 48 * 49 * <p> 50 * Access to the data object is provided through the {@code get()} method. So, code that wants to obtain the {@code ComplexObject} instance would simply look 51 * like this: 52 * </p> 53 * 54 * <pre> 55 * // Create an instance of the lazy initializer 56 * ComplexObjectInitializer initializer = new ComplexObjectInitializer(); 57 * ... 58 * // When the object is actually needed: 59 * ComplexObject cobj = initializer.get(); 60 * </pre> 61 * 62 * <p> 63 * If multiple threads call the {@code get()} method when the object has not yet been created, they are blocked until initialization completes. The algorithm 64 * guarantees that only a single instance of the wrapped object class is created, which is passed to all callers. Once initialized, calls to the {@code get()} 65 * method are pretty fast because no synchronization is needed (only an access to a <b>volatile</b> member field). 66 * </p> 67 * 68 * @since 3.0 69 * @param <T> the type of the object managed by the initializer. 70 */ 71 public class LazyInitializer<T> extends AbstractConcurrentInitializer<T, ConcurrentException> { 72 73 /** 74 * Builds a new instance. 75 * 76 * @param <T> the type of the object managed by the initializer. 77 * @param <I> the type of the initializer managed by this builder. 78 * @since 3.14.0 79 */ 80 public static class Builder<I extends LazyInitializer<T>, T> extends AbstractBuilder<I, T, Builder<I, T>, ConcurrentException> { 81 82 @SuppressWarnings("unchecked") 83 @Override 84 public I get() { 85 return (I) new LazyInitializer(getInitializer(), getCloser()); 86 } 87 88 } 89 90 /** 91 * A unique value indicating an un-initialzed instance. 92 */ 93 private static final Object NO_INIT = new Object(); 94 95 /** 96 * Creates a new builder. 97 * 98 * @param <T> the type of object to build. 99 * @return a new builder. 100 * @since 3.14.0 101 */ 102 public static <T> Builder<LazyInitializer<T>, T> builder() { 103 return new Builder<>(); 104 } 105 106 /** Stores the managed object. */ 107 @SuppressWarnings("unchecked") 108 private volatile T object = (T) NO_INIT; 109 110 /** 111 * Constructs a new instance. 112 */ 113 public LazyInitializer() { 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 LazyInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer) { 124 super(initializer, closer); 125 } 126 127 /** 128 * Returns the object wrapped by this instance. On first access the object is created. After that it is cached and can be accessed pretty fast. 129 * 130 * @return the object initialized by this {@link LazyInitializer} 131 * @throws ConcurrentException if an error occurred during initialization of the object 132 */ 133 @Override 134 public T get() throws ConcurrentException { 135 // use a temporary variable to reduce the number of reads of the 136 // volatile field 137 T result = object; 138 139 if (result == NO_INIT) { 140 synchronized (this) { 141 result = object; 142 if (result == NO_INIT) { 143 object = result = initialize(); 144 } 145 } 146 } 147 148 return result; 149 } 150 151 /** 152 * {@inheritDoc} 153 */ 154 @Override 155 protected ConcurrentException getTypedException(Exception e) { 156 return new ConcurrentException(e); 157 } 158 159 /** 160 * Tests whether this instance is initialized. Once initialized, always returns true. 161 * 162 * @return whether this instance is initialized. Once initialized, always returns true. 163 * @since 3.14.0 164 */ 165 @Override 166 public boolean isInitialized() { 167 return object != NO_INIT; 168 } 169 170 }