Java Driver Concurrency

The Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single MongoClient instance, and you can use it in every request. The MongoClient object maintains an internal pool of connections to the database (default maximum pool size of 100). For every request to the DB (find, insert, etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

Additionally in the case of a replica set and a read preference of secondary, the read operations will be distributed evenly across all secondaries. This means that within the same thread, a write followed by a read may be sent to different servers (master then slave). In turn the read operation may not see the data just written since replication is asynchronous.

DB and DBCollection are completely thread safe. In fact, they are cached so you get the same instance no matter what.

WriteConcern Option for Single Write Operation

Since by default a connection is given back to the pool after each request, you may wonder how calling getLastError() works after a write. You should actually use a write concern like WriteConcern.ACKNOWLEDGED instead of calling getLastError() manually. The driver will then call getLastError() before putting the connection back in the pool.

DBCollection coll...;
coll.insert(..., WriteConcern.ACKNOWLEDGED);

// is equivalent to

DB db...;
DBCollection coll...;
try {
   DBObject err = db.getLastError();
} finally {