Docs Menu
Docs Home
/ / /
Java Sync Driver
/ /

Limit Server Execution Time

On this page

  • Overview
  • timeoutMS Option
  • Accepted Timeout Values
  • Timeout Inheritance
  • Overrides
  • Transactions
  • Client Encryption
  • Cursors
  • Cursor Lifetime Mode
  • Cursor Iteration Mode
  • API Documentation

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.

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 the MongoClientSettings.Builder class

  • Setting the timeoutMS parameter 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);

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.

0

Specifies that operations never time out.

null or unset

Defers the timeout behavior to the following settings:
  • waitQueueTimeoutMS

  • socketTimeoutMS

  • wTimeoutMS

  • maxTimeMS

  • maxCommitTimeMS

These settings are deprecated and are ignored if you set timeoutMS.

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"));
}

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 timeoutMS.

For more information on overrides and specific options, see the following Overrides section.

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
}

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.

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

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);

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());
}
}

To learn more about using timeouts with the Java driver, see the following API documentation:

Back

Stable API