1 /* 2 * Copyright (C) 2023 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.util.concurrent; 16 17 import com.google.common.annotations.GwtCompatible; 18 import java.util.logging.Logger; 19 import org.checkerframework.checker.nullness.qual.Nullable; 20 21 /** A holder for a {@link Logger} that is initialized only when requested. */ 22 @GwtCompatible 23 @ElementTypesAreNonnullByDefault 24 final class LazyLogger { 25 private final String loggerName; 26 private volatile @Nullable Logger logger; 27 LazyLogger(Class<?> ownerOfLogger)28 LazyLogger(Class<?> ownerOfLogger) { 29 this.loggerName = ownerOfLogger.getName(); 30 } 31 get()32 Logger get() { 33 /* 34 * We use double-checked locking. We could the try racy single-check idiom, but that would 35 * depend on Logger not contain mutable state. 36 * 37 * We could use Suppliers.memoizingSupplier here, but I micro-optimized to this implementation 38 * to avoid the extra class for the lambda (and maybe more for memoizingSupplier itself) and the 39 * indirection. 40 * 41 * One thing to *avoid* is a change to make each Logger user use memoizingSupplier directly: 42 * That may introduce an extra class for each lambda (currently a dozen). 43 */ 44 Logger local = logger; 45 if (local != null) { 46 return local; 47 } 48 synchronized (this) { 49 local = logger; 50 if (local != null) { 51 return local; 52 } 53 return logger = Logger.getLogger(loggerName); 54 } 55 } 56 } 57