Skip to content

Commit b2f9813

Browse files
runningcodeclaude
andcommitted
ref(core): Hold the hostname cache on SentryOptions (JAVA-579)
HostnameCache was a process-wide static singleton. SentryOptions now holds one instance instead, wrapped in a LazyEvaluator because resolving the hostname blocks on InetAddress.getLocalHost(), which no Sentry.init should pay for up front. MainEventProcessor, MetricsApi and LoggerApi read the cache off the options they already hold. MainEventProcessor no longer memoizes the cache itself, since that duplicated the LazyEvaluator. MainEventProcessorTest no longer needs Mockito.mockStatic to intercept getInstance(); it overrides getHostnameCache() on the options instead, the way CheckInUtilsTest overrides getMonotonicTicker(). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 48811f6 commit b2f9813

9 files changed

Lines changed: 60 additions & 58 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
- Keep the Android feedback form available when its options configurator throws ([#6239](https://github.com/getsentry/sentry-java/pull/6239)).
2020
- Isolate nonfatal callback throwables while continuing to propagate fatal JVM errors ([#6251](https://github.com/getsentry/sentry-java/pull/6251)).
2121

22+
### Internal
23+
24+
- Hold the hostname cache on `SentryOptions` instead of a static singleton ([#6117](https://github.com/getsentry/sentry-java/pull/6117))
25+
2226
### Dependencies
2327

2428
- Bump Native SDK from v0.17.2 to v0.17.3 ([#6250](https://github.com/getsentry/sentry-java/pull/6250))

‎sentry/api/sentry.api‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,6 @@ public final class io/sentry/Hint {
694694

695695
public final class io/sentry/HostnameCache {
696696
public fun getHostname ()Ljava/lang/String;
697-
public static fun getInstance ()Lio/sentry/HostnameCache;
698697
}
699698

700699
public final class io/sentry/HttpBodyType : java/lang/Enum {
@@ -3808,6 +3807,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig {
38083807
public fun getFlushTimeoutMillis ()J
38093808
public fun getFullyDisplayedReporter ()Lio/sentry/FullyDisplayedReporter;
38103809
public fun getGestureTargetLocators ()Ljava/util/List;
3810+
public fun getHostnameCache ()Lio/sentry/HostnameCache;
38113811
public fun getIdleTimeout ()Ljava/lang/Long;
38123812
public fun getIgnoredCheckIns ()Ljava/util/List;
38133813
public fun getIgnoredErrors ()Ljava/util/List;

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

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

3-
import io.sentry.util.AutoClosableReentrantLock;
43
import io.sentry.util.Objects;
54
import java.net.InetAddress;
65
import java.util.concurrent.Callable;
@@ -26,8 +25,8 @@
2625
* purposes, the operation of retrieving the hostname will automatically fail after a period of time
2726
* defined by {@link #GET_HOSTNAME_TIMEOUT} without result.
2827
*
29-
* <p>HostnameCache is a singleton and its instance should be obtained through {@link
30-
* HostnameCache#getInstance()}.
28+
* <p>One instance is held per {@link SentryOptions} and should be obtained through {@link
29+
* SentryOptions#getHostnameCache()}.
3130
*/
3231
@ApiStatus.Internal
3332
public final class HostnameCache {
@@ -39,10 +38,6 @@ public final class HostnameCache {
3938
/** How long the worker thread may stay idle before it self-terminates. */
4039
private static final long THREAD_KEEP_ALIVE_SECONDS = 30;
4140

42-
private static volatile @Nullable HostnameCache INSTANCE;
43-
private static final @NotNull AutoClosableReentrantLock staticLock =
44-
new AutoClosableReentrantLock();
45-
4641
/** Time for which the cache is kept. */
4742
private final long cacheDuration;
4843

@@ -59,19 +54,7 @@ public final class HostnameCache {
5954

6055
private final @NotNull ExecutorService executorService;
6156

62-
public static @NotNull HostnameCache getInstance() {
63-
if (INSTANCE == null) {
64-
try (final @NotNull ISentryLifecycleToken ignored = staticLock.acquire()) {
65-
if (INSTANCE == null) {
66-
INSTANCE = new HostnameCache();
67-
}
68-
}
69-
}
70-
71-
return INSTANCE;
72-
}
73-
74-
private HostnameCache() {
57+
HostnameCache() {
7558
this(HOSTNAME_CACHE_DURATION);
7659
}
7760

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

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ public final class MainEventProcessor implements SentryEventProcessor {
2222
private final @NotNull SentryOptions options;
2323
private final @NotNull SentryThreadFactory sentryThreadFactory;
2424
private final @NotNull SentryExceptionFactory sentryExceptionFactory;
25-
private volatile @Nullable HostnameCache hostnameCache = null;
2625

2726
public MainEventProcessor(final @NotNull SentryOptions options) {
2827
this.options = options;
@@ -161,16 +160,7 @@ private void setServerName(final @NotNull SentryBaseEvent event) {
161160
}
162161

163162
if (options.isAttachServerName() && event.getServerName() == null) {
164-
ensureHostnameCache();
165-
if (hostnameCache != null) {
166-
event.setServerName(hostnameCache.getHostname());
167-
}
168-
}
169-
}
170-
171-
private void ensureHostnameCache() {
172-
if (hostnameCache == null) {
173-
hostnameCache = HostnameCache.getInstance();
163+
event.setServerName(options.getHostnameCache().getHostname());
174164
}
175165
}
176166

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,16 @@ public class SentryOptions implements RateLimiterConfig {
535535
private final @NotNull LazyEvaluator<SentryDateProvider> dateProvider =
536536
new LazyEvaluator<>(() -> new SentryAutoDateProvider());
537537

538+
/**
539+
* Cache of the local hostname, used when {@link #isAttachServerName()} is enabled.
540+
*
541+
* <p>Evaluated lazily because resolving the hostname blocks on {@code
542+
* InetAddress.getLocalHost()}, which no {@code Sentry.init} should pay for up front.
543+
*/
544+
@ApiStatus.Internal
545+
private final @NotNull LazyEvaluator<HostnameCache> hostnameCache =
546+
new LazyEvaluator<>(() -> new HostnameCache());
547+
538548
private final @NotNull List<IPerformanceCollector> performanceCollectors = new ArrayList<>();
539549

540550
/** Performance collector that collect performance stats while transactions run. */
@@ -3140,6 +3150,12 @@ public void setDateProvider(final @NotNull SentryDateProvider dateProvider) {
31403150
return JavaMonotonicTicker.getInstance();
31413151
}
31423152

3153+
/** Returns the hostname cache, resolving the hostname on first use. */
3154+
@ApiStatus.Internal
3155+
public @NotNull HostnameCache getHostnameCache() {
3156+
return hostnameCache.getValue();
3157+
}
3158+
31433159
/**
31443160
* Adds a ICollector.
31453161
*

‎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;
@@ -256,7 +255,7 @@ private void setServerName(
256255
"server.address",
257256
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
258257
} else if (options.isAttachServerName()) {
259-
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
258+
final @Nullable String hostname = options.getHostnameCache().getHostname();
260259
if (hostname != null) {
261260
attributes.put(
262261
"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;
@@ -241,7 +240,7 @@ private void setServerName(
241240
"server.address",
242241
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
243242
} else if (options.isAttachServerName()) {
244-
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
243+
final @Nullable String hostname = options.getHostnameCache().getHostname();
245244
if (hostname != null) {
246245
attributes.put(
247246
"server.address",

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

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import io.sentry.protocol.User
1010
import io.sentry.util.HintUtils
1111
import java.lang.RuntimeException
1212
import java.net.InetAddress
13-
import kotlin.test.AfterTest
1413
import kotlin.test.Test
1514
import kotlin.test.assertEquals
1615
import kotlin.test.assertFalse
@@ -19,7 +18,6 @@ import kotlin.test.assertNull
1918
import kotlin.test.assertSame
2019
import kotlin.test.assertTrue
2120
import org.awaitility.kotlin.await
22-
import org.mockito.Mockito
2321
import org.mockito.kotlin.mock
2422
import org.mockito.kotlin.reset
2523
import org.mockito.kotlin.times
@@ -28,17 +26,23 @@ import org.mockito.kotlin.whenever
2826

2927
class MainEventProcessorTest {
3028
class Fixture {
31-
val sentryOptions: SentryOptions =
32-
SentryOptions().apply {
33-
dsn = dsnString
34-
release = "release"
35-
dist = "dist"
36-
sdkVersion = SdkVersion("test", "1.2.3")
37-
}
3829
val scopes = mock<IScopes>()
3930
val getLocalhost = mock<InetAddress>()
31+
// Built in getSut() rather than here: the constructor resolves the hostname straight away,
32+
// so it has to run after getLocalhost is stubbed.
33+
lateinit var hostnameCache: HostnameCache
34+
val sentryOptions: SentryOptions =
35+
object : SentryOptions() {
36+
// Qualified: an unqualified name here would resolve to this override, not the field.
37+
override fun getHostnameCache(): HostnameCache = this@Fixture.hostnameCache
38+
}
39+
.apply {
40+
dsn = dsnString
41+
release = "release"
42+
dist = "dist"
43+
sdkVersion = SdkVersion("test", "1.2.3")
44+
}
4045
lateinit var sentryTracer: SentryTracer
41-
private val hostnameCacheMock = Mockito.mockStatic(HostnameCache::class.java)
4246

4347
fun getSut(
4448
attachThreads: Boolean = true,
@@ -76,21 +80,10 @@ class MainEventProcessorTest {
7680
}
7781
whenever(scopes.options).thenReturn(sentryOptions)
7882
sentryTracer = SentryTracer(TransactionContext("", ""), scopes)
79-
80-
val hostnameCache = HostnameCache(hostnameCacheDuration) { getLocalhost }
81-
hostnameCacheMock.`when`<Any> { HostnameCache.getInstance() }.thenReturn(hostnameCache)
83+
hostnameCache = HostnameCache(hostnameCacheDuration) { getLocalhost }
8284

8385
return MainEventProcessor(sentryOptions)
8486
}
85-
86-
fun teardown() {
87-
hostnameCacheMock.close()
88-
}
89-
}
90-
91-
@AfterTest
92-
fun teardown() {
93-
fixture.teardown()
9487
}
9588

9689
private val fixture = Fixture()

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package io.sentry
33
import com.google.common.truth.Truth.assertThat
44
import io.sentry.SentryOptions.RequestSize
55
import io.sentry.logger.ILoggerBatchProcessorFactory
6+
import io.sentry.test.getProperty
7+
import io.sentry.util.LazyEvaluator
68
import io.sentry.util.StringUtils
79
import java.io.File
810
import java.net.Proxy
@@ -1331,4 +1333,20 @@ class SentryOptionsTest {
13311333
options.scopesStorageFactory = null
13321334
assertNull(options.scopesStorageFactory)
13331335
}
1336+
1337+
private fun SentryOptions.peekHostnameCache(): HostnameCache? =
1338+
getProperty<LazyEvaluator<HostnameCache>>("hostnameCache").getProperty("value")
1339+
1340+
@Test
1341+
fun `hostname is resolved on first use, not when options are constructed`() {
1342+
val options = SentryOptions()
1343+
1344+
assertThat(options.peekHostnameCache()).isNull()
1345+
1346+
val cache = options.hostnameCache
1347+
1348+
// Also keeps the assertion above honest: peek does report a cache once one exists.
1349+
assertThat(options.peekHostnameCache()).isSameInstanceAs(cache)
1350+
assertThat(options.hostnameCache).isSameInstanceAs(cache)
1351+
}
13341352
}

0 commit comments

Comments
 (0)