Skip to content

Commit 1a2b977

Browse files
committed
#6313 handle out-of-order scope closure
1 parent a465671 commit 1a2b977

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,14 @@ static ObservationRegistry create() {
7373
*/
7474
void setCurrentObservationScope(Observation.@Nullable Scope current);
7575

76+
/**
77+
* Sets the observation scope as current only if the candidate is present in the registry.
78+
* @param candidate observation scope
79+
*/
80+
default void setCurrentObservationScopeIfExists(Observation.@Nullable Scope candidate) {
81+
setCurrentObservationScope(candidate);
82+
}
83+
7684
/**
7785
* Configuration options for this registry.
7886
* @return observation configuration

micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,10 @@ else if (currentObservation != null && !currentObservation.isNoop()) {
313313
else {
314314
log.trace("NoOp observation used with SimpleScope");
315315
}
316-
this.registry.setCurrentObservationScope(previousObservationScope);
316+
// DB connections might be closed out of order, so only set the previous scope
317+
// as current if it has not been already closed (by checking if it still exists
318+
// in the registry).
319+
this.registry.setCurrentObservationScopeIfExists(previousObservationScope);
317320
}
318321

319322
private @Nullable SimpleScope getLastScope(SimpleScope simpleScope) {

micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservationRegistry.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,22 @@ public void setCurrentObservationScope(Observation.@Nullable Scope current) {
5050
localObservationScope.set(current);
5151
}
5252

53+
@Override
54+
public void setCurrentObservationScopeIfExists(Observation.@Nullable Scope candidate) {
55+
if (candidate == null) {
56+
setCurrentObservationScope(null);
57+
} else {
58+
Observation.Scope scope = localObservationScope.get();
59+
while (scope != null) {
60+
if (scope.equals(candidate)) {
61+
setCurrentObservationScope(candidate);
62+
break;
63+
}
64+
scope = scope.getPreviousObservationScope();
65+
}
66+
}
67+
}
68+
5369
@Override
5470
public ObservationConfig observationConfig() {
5571
return this.observationConfig;

0 commit comments

Comments
 (0)