Skip to content

Commit 52761fd

Browse files
runningcodeclaude
andcommitted
ref(core): Hold the hostname cache on SentryOptions (JAVA-579)
HostnameCache was a process-wide static singleton whose constructor reached for JavaMonotonicTicker.getInstance() directly. That was the last place in the SDK hard-coding a ticker rather than taking one from options, so the cache measured its TTL on System.nanoTime() even where options supply an elapsedRealtimeNanos()-backed ticker that counts deep sleep. SentryOptions now holds one instance, built from getMonotonicTicker() the same way RateLimiter(SentryOptions) is. It is wrapped in a LazyEvaluator because resolving the hostname blocks on InetAddress.getLocalHost(), which no Sentry.init should pay for up front; deferring also means the SentryAndroidOptions override is in effect by the time the ticker is read. MainEventProcessor still closes the cache, and now drops both its own reference and the options-held one. Both it and the options outlive Scopes.close(isRestarting = true), so a closed cache left in either place would never refresh the hostname again. MainEventProcessorTest no longer needs Mockito.mockStatic to intercept getInstance(); it sets the cache on options instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent fdd896b commit 52761fd

8 files changed

Lines changed: 106 additions & 43 deletions

File tree

‎sentry/api/sentry.api‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,6 @@ public final class io/sentry/Hint {
633633

634634
public final class io/sentry/HostnameCache {
635635
public fun getHostname ()Ljava/lang/String;
636-
public static fun getInstance ()Lio/sentry/HostnameCache;
637636
}
638637

639638
public final class io/sentry/HttpStatusCodeRange {
@@ -3716,6 +3715,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig {
37163715
public fun getFlushTimeoutMillis ()J
37173716
public fun getFullyDisplayedReporter ()Lio/sentry/FullyDisplayedReporter;
37183717
public fun getGestureTargetLocators ()Ljava/util/List;
3718+
public fun getHostnameCache ()Lio/sentry/HostnameCache;
37193719
public fun getIdleTimeout ()Ljava/lang/Long;
37203720
public fun getIgnoredCheckIns ()Ljava/util/List;
37213721
public fun getIgnoredErrors ()Ljava/util/List;
@@ -3827,6 +3827,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig {
38273827
public fun isTraceSampling ()Z
38283828
public fun isTracingEnabled ()Z
38293829
public fun merge (Lio/sentry/ExternalOptions;)V
3830+
public fun resetHostnameCache ()V
38303831
public fun setAppStartExtender (Lio/sentry/IAppStartExtender;)V
38313832
public fun setAttachServerName (Z)V
38323833
public fun setAttachStacktrace (Z)V
@@ -3887,6 +3888,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig {
38873888
public fun setFullyDisplayedReporter (Lio/sentry/FullyDisplayedReporter;)V
38883889
public fun setGestureTargetLocators (Ljava/util/List;)V
38893890
public fun setGlobalHubMode (Ljava/lang/Boolean;)V
3891+
public fun setHostnameCache (Lio/sentry/HostnameCache;)V
38903892
public fun setIdleTimeout (Ljava/lang/Long;)V
38913893
public fun setIgnoredCheckIns (Ljava/util/List;)V
38923894
public fun setIgnoredErrors (Ljava/util/List;)V

‎sentry/src/main/java/io/sentry/HostnameCache.java‎

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package io.sentry;
22

33
import io.sentry.time.Deadline;
4-
import io.sentry.time.JavaMonotonicTicker;
54
import io.sentry.time.MonotonicTicker;
6-
import io.sentry.util.AutoClosableReentrantLock;
75
import io.sentry.util.Objects;
86
import java.net.InetAddress;
97
import java.util.concurrent.Callable;
@@ -28,8 +26,8 @@
2826
* performance purposes, the operation of retrieving the hostname will automatically fail after a
2927
* period of time defined by {@link #GET_HOSTNAME_TIMEOUT} without result.
3028
*
31-
* <p>HostnameCache is a singleton and its instance should be obtained through {@link
32-
* HostnameCache#getInstance()}.
29+
* <p>One instance is held per {@link SentryOptions} and should be obtained through {@link
30+
* SentryOptions#getHostnameCache()}.
3331
*/
3432
@ApiStatus.Internal
3533
public final class HostnameCache {
@@ -41,10 +39,6 @@ public final class HostnameCache {
4139
/** How long the worker thread may stay idle before it self-terminates. */
4240
private static final long THREAD_KEEP_ALIVE_SECONDS = 30;
4341

44-
private static volatile @Nullable HostnameCache INSTANCE;
45-
private static final @NotNull AutoClosableReentrantLock staticLock =
46-
new AutoClosableReentrantLock();
47-
4842
private final @NotNull MonotonicTicker ticker;
4943

5044
/** Current value for hostname (might change over time). */
@@ -60,22 +54,10 @@ public final class HostnameCache {
6054

6155
private final @NotNull ExecutorService executorService;
6256

63-
public static @NotNull HostnameCache getInstance() {
64-
if (INSTANCE == null) {
65-
try (final @NotNull ISentryLifecycleToken ignored = staticLock.acquire()) {
66-
if (INSTANCE == null) {
67-
INSTANCE = new HostnameCache();
68-
}
69-
}
70-
}
71-
72-
return INSTANCE;
73-
}
74-
75-
private HostnameCache() {
57+
HostnameCache(final @NotNull SentryOptions options) {
7658
// avoid method refs on Android due to some issues with older AGP setups
7759
// noinspection Convert2MethodRef
78-
this(() -> InetAddress.getLocalHost(), JavaMonotonicTicker.getInstance());
60+
this(() -> InetAddress.getLocalHost(), options.getMonotonicTicker());
7961
}
8062

8163
/**

‎sentry/src/main/java/io/sentry/MainEventProcessor.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ private void setServerName(final @NotNull SentryBaseEvent event) {
172172

173173
private void ensureHostnameCache() {
174174
if (hostnameCache == null) {
175-
hostnameCache = HostnameCache.getInstance();
175+
hostnameCache = options.getHostnameCache();
176176
}
177177
}
178178

@@ -275,6 +275,10 @@ private boolean isCachedHint(final @NotNull Hint hint) {
275275
public void close() throws IOException {
276276
if (hostnameCache != null) {
277277
hostnameCache.close();
278+
// Both this processor and the options outlive a restart, so a closed cache left in either
279+
// place would never refresh the hostname again.
280+
hostnameCache = null;
281+
options.resetHostnameCache();
278282
}
279283
}
280284

‎sentry/src/main/java/io/sentry/SentryOptions.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,17 @@ public class SentryOptions implements RateLimiterConfig {
530530
private final @NotNull LazyEvaluator<SentryDateProvider> dateProvider =
531531
new LazyEvaluator<>(() -> new SentryAutoDateProvider());
532532

533+
/**
534+
* Cache of the local hostname, used when {@link #isAttachServerName()} is enabled.
535+
*
536+
* <p>Evaluated lazily because resolving the hostname blocks on {@code
537+
* InetAddress.getLocalHost()}, which no {@code Sentry.init} should pay for up front. Deferring
538+
* also means {@link #getMonotonicTicker()} is read after subclasses have overridden it.
539+
*/
540+
@ApiStatus.Internal
541+
private final @NotNull LazyEvaluator<HostnameCache> hostnameCache =
542+
new LazyEvaluator<>(() -> new HostnameCache(this));
543+
533544
private final @NotNull List<IPerformanceCollector> performanceCollectors = new ArrayList<>();
534545

535546
/** Performance collector that collect performance stats while transactions run. */
@@ -3092,6 +3103,28 @@ public void setDateProvider(final @NotNull SentryDateProvider dateProvider) {
30923103
return JavaMonotonicTicker.getInstance();
30933104
}
30943105

3106+
/** Returns the hostname cache, resolving the hostname on first use. */
3107+
@ApiStatus.Internal
3108+
public @NotNull HostnameCache getHostnameCache() {
3109+
return hostnameCache.getValue();
3110+
}
3111+
3112+
@ApiStatus.Internal
3113+
public void setHostnameCache(final @NotNull HostnameCache hostnameCache) {
3114+
this.hostnameCache.setValue(hostnameCache);
3115+
}
3116+
3117+
/**
3118+
* Discards the cached instance, so that the next {@link #getHostnameCache()} builds a new one.
3119+
*
3120+
* <p>Called after the cache has been closed, because these options outlive a restart and a closed
3121+
* cache can no longer resolve anything.
3122+
*/
3123+
@ApiStatus.Internal
3124+
public void resetHostnameCache() {
3125+
hostnameCache.resetValue();
3126+
}
3127+
30953128
/**
30963129
* Adds a ICollector.
30973130
*

‎sentry/src/main/java/io/sentry/logger/LoggerApi.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package io.sentry.logger;
22

3-
import io.sentry.HostnameCache;
43
import io.sentry.IScope;
54
import io.sentry.ISpan;
65
import io.sentry.PropagationContext;
@@ -263,7 +262,7 @@ private void setServerName(
263262
"server.address",
264263
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
265264
} else if (options.isAttachServerName()) {
266-
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
265+
final @Nullable String hostname = options.getHostnameCache().getHostname();
267266
if (hostname != null) {
268267
attributes.put(
269268
"server.address",

‎sentry/src/main/java/io/sentry/metrics/MetricsApi.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package io.sentry.metrics;
22

3-
import io.sentry.HostnameCache;
43
import io.sentry.IScope;
54
import io.sentry.ISpan;
65
import io.sentry.PropagationContext;
@@ -250,7 +249,7 @@ private void setServerName(
250249
"server.address",
251250
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
252251
} else if (options.isAttachServerName()) {
253-
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
252+
final @Nullable String hostname = options.getHostnameCache().getHostname();
254253
if (hostname != null) {
255254
attributes.put(
256255
"server.address",

‎sentry/src/test/java/io/sentry/MainEventProcessorTest.kt‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,13 @@ import io.sentry.util.HintUtils
1111
import java.lang.RuntimeException
1212
import java.net.InetAddress
1313
import java.util.concurrent.TimeUnit
14-
import kotlin.test.AfterTest
1514
import kotlin.test.Test
1615
import kotlin.test.assertEquals
1716
import kotlin.test.assertFalse
1817
import kotlin.test.assertNotNull
1918
import kotlin.test.assertNull
2019
import kotlin.test.assertSame
2120
import kotlin.test.assertTrue
22-
import org.mockito.Mockito
2321
import org.mockito.kotlin.mock
2422
import org.mockito.kotlin.reset
2523
import org.mockito.kotlin.times
@@ -39,7 +37,6 @@ class MainEventProcessorTest {
3937
val getLocalhost = mock<InetAddress>()
4038
val hostnameCacheTicker = TestMonotonicTicker()
4139
lateinit var sentryTracer: SentryTracer
42-
private val hostnameCacheMock = Mockito.mockStatic(HostnameCache::class.java)
4340

4441
fun getSut(
4542
attachThreads: Boolean = true,
@@ -77,20 +74,10 @@ class MainEventProcessorTest {
7774
whenever(scopes.options).thenReturn(sentryOptions)
7875
sentryTracer = SentryTracer(TransactionContext("", ""), scopes)
7976

80-
val hostnameCache = HostnameCache({ getLocalhost }, hostnameCacheTicker)
81-
hostnameCacheMock.`when`<Any> { HostnameCache.getInstance() }.thenReturn(hostnameCache)
77+
sentryOptions.setHostnameCache(HostnameCache({ getLocalhost }, hostnameCacheTicker))
8278

8379
return MainEventProcessor(sentryOptions)
8480
}
85-
86-
fun teardown() {
87-
hostnameCacheMock.close()
88-
}
89-
}
90-
91-
@AfterTest
92-
fun teardown() {
93-
fixture.teardown()
9481
}
9582

9683
private val fixture = Fixture()
@@ -576,9 +563,14 @@ class MainEventProcessorTest {
576563
val sut = fixture.getSut(serverName = null)
577564

578565
sut.process(SentryTransaction(fixture.sentryTracer), Hint())
566+
val hostnameCache = assertNotNull(sut.hostnameCache)
579567

580568
sut.close()
581-
assertNotNull(sut.hostnameCache) { assertTrue(it.isClosed) }
569+
570+
assertTrue(hostnameCache.isClosed)
571+
// Dropped on close so that a restart resolves the hostname again instead of reusing a cache
572+
// whose executor is shut down.
573+
assertNull(sut.hostnameCache)
582574
}
583575

584576
@Test

‎sentry/src/test/java/io/sentry/SentryOptionsTest.kt‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
package io.sentry
22

3+
import com.google.common.truth.Truth.assertThat
34
import io.sentry.SentryOptions.RequestSize
45
import io.sentry.logger.ILoggerBatchProcessorFactory
6+
import io.sentry.test.getProperty
7+
import io.sentry.time.MonotonicTicker
8+
import io.sentry.time.TestMonotonicTicker
9+
import io.sentry.util.LazyEvaluator
510
import io.sentry.util.StringUtils
611
import java.io.File
12+
import java.net.InetAddress
713
import java.net.Proxy
14+
import java.util.concurrent.Callable
815
import kotlin.test.Test
916
import kotlin.test.assertEquals
1017
import kotlin.test.assertFailsWith
@@ -1167,4 +1174,49 @@ class SentryOptionsTest {
11671174
options.scopesStorageFactory = null
11681175
assertNull(options.scopesStorageFactory)
11691176
}
1177+
1178+
private fun SentryOptions.peekHostnameCache(): HostnameCache? =
1179+
getProperty<LazyEvaluator<HostnameCache>>("hostnameCache").getProperty("value")
1180+
1181+
@Test
1182+
fun `constructing options does not resolve the hostname`() {
1183+
val options = SentryOptions()
1184+
assertThat(options.peekHostnameCache()).isNull()
1185+
1186+
// Asserting that peek reports an evaluated cache keeps the check above from passing vacuously.
1187+
options.hostnameCache = HostnameCache(Callable { mock<InetAddress>() }, TestMonotonicTicker())
1188+
assertThat(options.peekHostnameCache()).isNotNull()
1189+
}
1190+
1191+
@Test
1192+
fun `hostnameCache is created once and reused`() {
1193+
val options = SentryOptions()
1194+
val cache = HostnameCache(Callable { mock<InetAddress>() }, TestMonotonicTicker())
1195+
options.hostnameCache = cache
1196+
1197+
assertThat(options.hostnameCache).isSameInstanceAs(cache)
1198+
assertThat(options.hostnameCache).isSameInstanceAs(cache)
1199+
}
1200+
1201+
@Test
1202+
fun `resetHostnameCache discards the cached instance`() {
1203+
val options = SentryOptions()
1204+
options.hostnameCache = HostnameCache(Callable { mock<InetAddress>() }, TestMonotonicTicker())
1205+
1206+
options.resetHostnameCache()
1207+
1208+
assertThat(options.peekHostnameCache()).isNull()
1209+
}
1210+
1211+
@Test
1212+
fun `hostnameCache measures its lifetime on the options ticker`() {
1213+
val ticker = TestMonotonicTicker()
1214+
val options =
1215+
object : SentryOptions() {
1216+
override fun getMonotonicTicker(): MonotonicTicker = ticker
1217+
}
1218+
1219+
assertThat(options.hostnameCache.getProperty<MonotonicTicker>("ticker"))
1220+
.isSameInstanceAs(ticker)
1221+
}
11701222
}

0 commit comments

Comments
 (0)