@@ -40,6 +40,8 @@ public class TimeoutContext {
40
40
41
41
@ Nullable
42
42
private Timeout timeout ;
43
+ @ Nullable
44
+ private Timeout computedServerSelectionTimeout ;
43
45
private long minRoundTripTimeMS = 0 ;
44
46
45
47
public static MongoOperationTimeoutException createMongoTimeoutException () {
@@ -183,14 +185,17 @@ public long getWriteTimeoutMS() {
183
185
return timeoutOrAlternative (0 );
184
186
}
185
187
188
+ public int getConnectTimeoutMs () {
189
+ return (int ) calculateMin (getTimeoutSettings ().getConnectTimeoutMS ());
190
+ }
186
191
187
192
public void resetTimeout () {
188
193
assertNotNull (timeout );
189
194
timeout = calculateTimeout (timeoutSettings .getTimeoutMS ());
190
195
}
191
196
192
197
/**
193
- * Resest the timeout if this timeout context is being used by pool maintenance
198
+ * Resets the timeout if this timeout context is being used by pool maintenance
194
199
*/
195
200
public void resetMaintenanceTimeout () {
196
201
if (isMaintenanceContext && timeout != null && !timeout .isInfinite ()) {
@@ -258,17 +263,34 @@ public static Timeout calculateTimeout(@Nullable final Long timeoutMS) {
258
263
}
259
264
260
265
public Timeout computedServerSelectionTimeout () {
261
- long ms = getTimeoutSettings ().getServerSelectionTimeoutMS ();
262
- Timeout serverSelectionTimeout = StartTime .now ().timeoutAfterOrInfiniteIfNegative (ms , MILLISECONDS );
263
- return serverSelectionTimeout .orEarlier (timeout );
266
+ if (computedServerSelectionTimeout == null ) {
267
+ computedServerSelectionTimeout = StartTime .now ()
268
+ .timeoutAfterOrInfiniteIfNegative (getTimeoutSettings ().getServerSelectionTimeoutMS (), MILLISECONDS )
269
+ .orEarlier (timeout );
270
+ }
271
+ return computedServerSelectionTimeout ;
272
+ }
273
+
274
+ public TimeoutContext withComputedServerSelectionTimeoutContext () {
275
+ if (!hasTimeoutMS ()) {
276
+ // Without timeoutMS keep the legacy timeout behavior
277
+ computedServerSelectionTimeout = null ;
278
+ return this ;
279
+ } else if (computedServerSelectionTimeout == null ) {
280
+ // Reusing a pooled connection
281
+ return this ;
282
+ }
283
+
284
+ TimeoutContext timeoutContext = Objects .equals (computedServerSelectionTimeout , timeout )
285
+ ? this : new TimeoutContext (false , timeoutSettings , computedServerSelectionTimeout );
286
+ computedServerSelectionTimeout = null ;
287
+ return timeoutContext ;
264
288
}
265
289
266
290
public Timeout startWaitQueueTimeout (final StartTime checkoutStart ) {
267
291
final long ms = getTimeoutSettings ().getMaxWaitTimeMS ();
268
292
return checkoutStart .timeoutAfterOrInfiniteIfNegative (ms , MILLISECONDS );
269
293
}
270
294
271
- public int getConnectTimeoutMs () {
272
- return (int ) getTimeoutSettings ().getConnectTimeoutMS ();
273
- }
295
+
274
296
}
0 commit comments