diff --git a/driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java b/driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java index e37e20d8378..b95686b4b6b 100644 --- a/driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java +++ b/driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java @@ -94,7 +94,13 @@ public void close() { try { closing = true; serverSessionPool.close(); - endClosedSessions(); + + List identifiers; + synchronized (this) { + identifiers = new ArrayList(closedSessionIdentifiers); + closedSessionIdentifiers.clear(); + } + endClosedSessions(identifiers); } finally { closed = true; } @@ -111,14 +117,21 @@ private void closeSession(final ServerSessionImpl serverSession) { return; } - closedSessionIdentifiers.add(serverSession.getIdentifier()); - if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) { - endClosedSessions(); + List identifiers = null; + synchronized (this) { + closedSessionIdentifiers.add(serverSession.getIdentifier()); + if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) { + identifiers = new ArrayList(closedSessionIdentifiers); + closedSessionIdentifiers.clear(); + } + } + if (identifiers != null) { + endClosedSessions(identifiers); } } - private void endClosedSessions() { - if (closedSessionIdentifiers.isEmpty()) { + private void endClosedSessions(final List identifiers) { + if (identifiers.isEmpty()) { return; } @@ -141,12 +154,11 @@ public List select(final ClusterDescription clusterDescriptio }).getConnection(); try { connection.command("admin", - new BsonDocument("endSessions", new BsonArray(closedSessionIdentifiers)), new NoOpFieldNameValidator(), + new BsonDocument("endSessions", new BsonArray(identifiers)), new NoOpFieldNameValidator(), ReadPreference.primaryPreferred(), new BsonDocumentCodec(), NoOpSessionContext.INSTANCE); } catch (MongoException e) { // ignore exceptions } finally { - closedSessionIdentifiers.clear(); connection.release(); } }