Skip to content

Commit 247e51f

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

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@ 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
78+
* registry.
79+
* @param candidate observation scope
80+
*/
81+
default void setCurrentObservationScopeIfExists(Observation.@Nullable Scope candidate) {
82+
setCurrentObservationScope(candidate);
83+
}
84+
7685
/**
7786
* Configuration options for this registry.
7887
* @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
318+
// exists 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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,23 @@ 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+
}
58+
else {
59+
Observation.Scope scope = localObservationScope.get();
60+
while (scope != null) {
61+
if (scope.equals(candidate)) {
62+
setCurrentObservationScope(candidate);
63+
break;
64+
}
65+
scope = scope.getPreviousObservationScope();
66+
}
67+
}
68+
}
69+
5370
@Override
5471
public ObservationConfig observationConfig() {
5572
return this.observationConfig;

0 commit comments

Comments
 (0)