Skip to content

Commit 33b86f7

Browse files
jstewart148jyemin
authored andcommitted
Fix concurrency issue when closing sessions in ServerSessionPool
JAVA-3433
1 parent 6e06585 commit 33b86f7

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

driver-core/src/main/com/mongodb/internal/session/ServerSessionPool.java

+20-8
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,13 @@ public void close() {
9494
try {
9595
closing = true;
9696
serverSessionPool.close();
97-
endClosedSessions();
97+
98+
List<BsonDocument> identifiers;
99+
synchronized (this) {
100+
identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers);
101+
closedSessionIdentifiers.clear();
102+
}
103+
endClosedSessions(identifiers);
98104
} finally {
99105
closed = true;
100106
}
@@ -111,14 +117,21 @@ private void closeSession(final ServerSessionImpl serverSession) {
111117
return;
112118
}
113119

114-
closedSessionIdentifiers.add(serverSession.getIdentifier());
115-
if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) {
116-
endClosedSessions();
120+
List<BsonDocument> identifiers = null;
121+
synchronized (this) {
122+
closedSessionIdentifiers.add(serverSession.getIdentifier());
123+
if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) {
124+
identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers);
125+
closedSessionIdentifiers.clear();
126+
}
127+
}
128+
if (identifiers != null) {
129+
endClosedSessions(identifiers);
117130
}
118131
}
119132

120-
private void endClosedSessions() {
121-
if (closedSessionIdentifiers.isEmpty()) {
133+
private void endClosedSessions(final List<BsonDocument> identifiers) {
134+
if (identifiers.isEmpty()) {
122135
return;
123136
}
124137

@@ -141,12 +154,11 @@ public List<ServerDescription> select(final ClusterDescription clusterDescriptio
141154
}).getConnection();
142155
try {
143156
connection.command("admin",
144-
new BsonDocument("endSessions", new BsonArray(closedSessionIdentifiers)), new NoOpFieldNameValidator(),
157+
new BsonDocument("endSessions", new BsonArray(identifiers)), new NoOpFieldNameValidator(),
145158
ReadPreference.primaryPreferred(), new BsonDocumentCodec(), NoOpSessionContext.INSTANCE);
146159
} catch (MongoException e) {
147160
// ignore exceptions
148161
} finally {
149-
closedSessionIdentifiers.clear();
150162
connection.release();
151163
}
152164
}

0 commit comments

Comments
 (0)