@@ -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