0

Its document says:

The client object is thread-safe and has connection-pooling built in.

This probably means we can create a single global MongoClient and share it across multiple threads. But when do we call MongoClient.close? Should it be called by each thread after that thread has finished database access, or should it be called only after all threads are done? If one thread calls MongoClient.close, does that affect other threads that are accessing the database? Finally, should we reuse closed client instance or create a new one for the next database access?

Cyker
  • 9,946
  • 8
  • 65
  • 93
  • In case of .net and [java](https://stackoverflow.com/questions/19938153/do-i-need-to-explicitly-close-connection), i believe python work same way, mongo client manage connections itself, you don't need to close them. It will give you free connection form a pool, if no connection available your thread will wait for one to become free. Number of connection, they lifetime and other behaviors controlled via connection properties or connection string. [mongo docs](https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options) – Artyom Jan 11 '19 at 09:53
  • @Artyom The pool has limited size. So if one thread is done it should release its resources so that others *don't have to wait*. That's why I think there is a `close` method. But its doc doesn't say much about multi-threading. – Cyker Jan 11 '19 at 10:41
  • you right about pool size, but it seems mongo drivers (at least .net and java) doing it behind the scene and return connection to pool as soon as it finish previous request. You can easily test it by doing some parallel loop with amount of request bigger then amount of maxPoolSize. – Artyom Jan 11 '19 at 12:21

0 Answers0