From 0bd319372afe83bc72d5d20533fee30a10fbbffe Mon Sep 17 00:00:00 2001 From: cpovirk Date: Wed, 21 Jun 2023 07:22:32 -0700 Subject: [PATCH] Delay initializing the `CacheBuilder` logger until it is needed. This is progress toward addressing the Java agent / `premain` problem discussed in https://github.com/google/guava/issues/6566. (And we're careful to avoid lambdas and method references so as to avoid https://github.com/google/guava/issues/6565.) RELNOTES=Fixed some problems with [using Guava from a Java Agent](https://github.com/google/guava/issues/6566). (But we don't test that configuration, and we don't know how well we'll be able to keep it working.) PiperOrigin-RevId: 542247494 --- .../guava/src/com/google/common/cache/CacheBuilder.java | 8 ++++++-- guava/src/com/google/common/cache/CacheBuilder.java | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/android/guava/src/com/google/common/cache/CacheBuilder.java b/android/guava/src/com/google/common/cache/CacheBuilder.java index 69b095d7e307..5d21c5b1833f 100644 --- a/android/guava/src/com/google/common/cache/CacheBuilder.java +++ b/android/guava/src/com/google/common/cache/CacheBuilder.java @@ -271,7 +271,10 @@ public long read() { } }; - private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName()); + // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566 + private static final class LoggerHolder { + static final Logger logger = Logger.getLogger(CacheBuilder.class.getName()); + } static final int UNSET_INT = -1; @@ -950,7 +953,8 @@ private void checkWeightWithWeigher() { checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight"); } else { if (maximumWeight == UNSET_INT) { - logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight"); + LoggerHolder.logger.log( + Level.WARNING, "ignoring weigher specified without maximumWeight"); } } } diff --git a/guava/src/com/google/common/cache/CacheBuilder.java b/guava/src/com/google/common/cache/CacheBuilder.java index 6e6458651397..bbb2b185b5f5 100644 --- a/guava/src/com/google/common/cache/CacheBuilder.java +++ b/guava/src/com/google/common/cache/CacheBuilder.java @@ -272,7 +272,10 @@ public long read() { } }; - private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName()); + // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566 + private static final class LoggerHolder { + static final Logger logger = Logger.getLogger(CacheBuilder.class.getName()); + } static final int UNSET_INT = -1; @@ -1056,7 +1059,8 @@ private void checkWeightWithWeigher() { checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight"); } else { if (maximumWeight == UNSET_INT) { - logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight"); + LoggerHolder.logger.log( + Level.WARNING, "ignoring weigher specified without maximumWeight"); } } }