Overview
When you use the Java driver to perform a server operation, you can also limit the amount of time in which the server can finish the operation. To do so, specify a client-side operation timeout (CSOT). The timeout applies to all steps needed to complete the operation, including server selection, connection checkout, and server-side execution. When the timeout expires, the Java driver raises a timeout exception.
Note
Experimental Feature
The CSOT feature is experimental and might change in future driver releases.
timeoutMS Option
To specify a timeout when connecting to a MongoDB deployment, set the timeoutMS connection option to the timeout length in milliseconds. You can set the timeoutMS option in the following ways:
Calling the
timeout()method from theMongoClientSettings.BuilderclassSetting the
timeoutMSparameter in your connection string
The following code examples set a client-level timeout of 200 milliseconds. Select the MongoClientSettings or Connection
String tab to see the corresponding code.
MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("<connection string>")) .timeout(200L, MILLISECONDS) .build(); MongoClient mongoClient = MongoClients.create(settings);
String uri = "<connection string>/?timeoutMS=200"; MongoClient mongoClient = MongoClients.create(uri);
Accepted Timeout Values
The following table describes the timeout behavior corresponding to the accepted values for timeoutMS:
Value | Behavior |
|---|---|
Positive integer | Sets the timeout to use for operation completion. |
| Specifies that operations never time out. |
| Defers the timeout behavior to the following settings: These settings are deprecated and are ignored if you set |
If you specify the timeoutMS option, the driver automatically applies the specified timeout to each server operation. The following code example specifies a timeout of 200 milliseconds at the client level, and then calls the MongoCollection.insertOne() method:
MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("<connection string>")) .timeout(200L, MILLISECONDS) .build(); try (MongoClient mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("db"); MongoCollection<Document> collection = database.getCollection("people"); collection.insertOne(new Document("name", "Francine Loews")); }
Timeout Inheritance
When you specify the timeoutMS option, the driver applies the timeout according to the same inheritance behaviors as the other Java driver options. The following table describes how the timeout value is inherited at each level:
Level | Inheritance Description |
|---|---|
Operation | Takes the highest precedence and overrides the timeout options that you set at any other level. |
Transaction | Takes precedence over the timeout value that you set at the session, collection, database, or client level. |
Session | Applies to all transactions and operations within that session, unless you set a different timeout value at those levels. |
Database | Applies to all sessions and operations within that database, unless you set a different timeout value at those levels. |
Collection | Applies to all sessions and operations on that collection, unless you set a different timeout value at those levels. |
Client | Applies to all databases, collections, sessions, transactions, and operations within that client that do not otherwise specify |
For more information on overrides and specific options, see the following Overrides section.
Overrides
The Java driver supports various levels of configuration to control the behavior and performance of database operations.
You can specify a timeoutMS option at a more specific level to override the client-level configuration. The table in the preceding section describes the levels at which you can specify a timeout setting. This allows you to customize timeouts based on the needs of individual operations.
The following example demonstrates how a collection-level timeout configuration can override a client-level timeout configuration:
MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("<connection string>")) .timeout(200L, MILLISECONDS) .build(); try (MongoClient mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("db"); MongoCollection<Document> collection = database .getCollection("people") .withTimeout(300L, MILLISECONDS); // ... perform operations on MongoCollection }
Transactions
When you create a new ClientSession instance to implement a transaction, use the defaultTimeout() method when building a ClientSessionOptions instance. You can use this option to specify the timeout for the following methods:
The following code demonstrates how to set the defaultTimeout when instantiating a ClientSession:
ClientSessionOptions opts = ClientSessionOptions.builder() .defaultTimeout(200L, MILLISECONDS) .build(); ClientSession session = mongoClient.startSession(opts); // ... perform operations on ClientSession
If you do not specify the defaultTimeout, the driver uses the timeout value set on the parent MongoClient.
You can also set a transaction-level timeout by calling the timeout() method when building a TransactionOptions instance. Setting this option applies a timeout to all operations performed in the scope of the transaction:
TransactionOptions transactionOptions = TransactionOptions.builder() .timeout(200L, MILLISECONDS) .build();
To learn more about transactions, see the Transactions guide.
Client Encryption
When you use Client-Side Field Level Encryption (CSFLE), the driver uses the timeoutMS option to limit the time allowed for encryption and decryption operations. You can set a timeout option for your ClientEncryption instance by calling the timeout() method when building a ClientEncryptionSettings instance.
If you specify the timeout when you construct a ClientEncryption instance, the timeout controls the lifetime of all operations performed on that instance. If you do not provide a timeout when instantiating ClientEncryption, the instance inherits the timeout setting from the MongoClient used in the ClientEncryption constructor.
If you set timeoutMS both on the client and directly in ClientEncryption, the value provided to ClientEncryption takes precedence.
Cursors
Cursors offer configurable timeout settings when using the CSOT feature. You can adjust cursor handling by configuring either the cursor lifetime or cursor iteration mode. To configure the timeout mode, use the timeoutMode() method when performing any operation that returns an Iterable.
For operations that create cursors, the timeout setting can either cap the lifetime of the cursor or be applied separately to the original operation and all subsequent calls.
Note
Inherited Timeout
Setting a cursor timeout mode requires that you set a timeout either in the MongoClientSettings, on MongoDatabase, or on MongoCollection.
To learn more about cursors, see the Access Data From a Cursor guide.
Cursor Lifetime Mode
The cursor lifetime mode uses the timeout setting to limit the entire lifetime of a cursor. In this mode, your application must initialize the cursor, complete all calls to the cursor methods, and return all documents within the specified time limit. Otherwise, the cursor's lifetime expires and the driver raises a timeout error.
When you close a cursor by calling the close() method, the timeout resets for the killCursors command to ensure server-side resources are cleaned up.
The following example shows how to set a cursor timeout to ensure that the cursor is initialized and all documents are retrieved within the inherited timeout:
FindIterable<Document> cursorWithLifetimeTimeout = collection .find(gte("age", 40)) .timeoutMode(TimeoutMode.CURSOR_LIFETIME);
Cursor Iteration Mode
The cursor iteration mode sets the timeout to limit each call to the next(), hasNext(), and tryNext() methods. The timeout refreshes after each call completes. This is the default mode for all tailable cursors, such as the tailable cursors returned by the find() method on capped collections or change streams.
The following code example iterates over documents in the db.people collection by using a cursor with the ITERATION timeout mode, and then retrieves and prints the name field value for each document:
try (MongoCursor<Document> cursorWithIterationTimeout = collection .find(gte("age", 40)) .timeoutMode(TimeoutMode.ITERATION) .cursor() ) { while (cursorWithIterationTimeout.hasNext()) { System.out.println(cursorWithIterationTimeout.next().toJson()); } }
GridFS
You can set a timeout option for GridFS operations when instantiating a GridFSBucket by using the withTimeout() method. This timeout applies to all operations performed on the bucket, such as uploading and downloading data. If you do not set a timeout, the GridFSBucket instance inherits the timeout setting from the MongoDatabase it is created with.
The following code demonstrates how to set a timeout when instantiating a GridFSBucket:
GridFSBucket gridFSBucket = GridFSBuckets .create(database) .withTimeout(200L, MILLISECONDS);
Important
InputStream Timeout Support
When you call the uploadFromStream() method on a GridFSBucket that has an operation timeout, timeout breaches might occur because the InputStream class lacks inherent read timeout support. This might extend the operation beyond the specified timeout limit, causing a timeout exception.
API Documentation
To learn more about using timeouts with the Java driver, see the following API documentation: