Skip to content

Commit

Permalink
fix(session): avoid cache exceptional session creation future (#189)
Browse files Browse the repository at this point in the history
* fix(session): do not cache failed future

* fix typo

* fix the spotless
  • Loading branch information
mattisonchao authored Oct 11, 2024
1 parent 36577ec commit 439666f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,14 @@ public CompletableFuture<Session> getSession(long shardId) {
new IllegalStateException("session manager has been closed"));
}

return sessionsByShardId.computeIfAbsent(shardId, s -> factory.create(shardId));
return sessionsByShardId.compute(
shardId,
(key, existing) -> {
if (existing != null && !existing.isCompletedExceptionally()) {
return existing;
}
return factory.create(shardId);
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,29 @@ void existingSession() {
verifyNoMoreInteractions(factory, session);
}

@Test
void existingSessionWithFailure() {
var shardId = 1L;
// first failed
when(factory.create(shardId))
.thenReturn(CompletableFuture.failedFuture(new IllegalStateException("failed")));
var session1 = manager.getSession(shardId);
assertThat(session1).isCompletedExceptionally();
verify(factory, times(1)).create(shardId);

// second should be success
when(factory.create(shardId)).thenReturn(CompletableFuture.completedFuture(session));
var session2 = manager.getSession(shardId);
assertThat(session2).isCompletedWithValue(session);
verify(factory, times(2)).create(shardId);

// third should be cache
var session3 = manager.getSession(shardId);
assertThat(session3).isSameAs(session2);
verify(factory, times(2)).create(shardId);
verifyNoMoreInteractions(factory, session);
}

@Test
void close() throws Exception {
var shardId = 5L;
Expand Down

0 comments on commit 439666f

Please sign in to comment.