Can MongoCollection (Java) be shared by multiple threads?

It is possible to share a MongoCollection from multiple threads?

I’m initializing the MongoDatabase and MongoCollection in a @PostConstruct (I’m using Quarkus), so it is stored in an @ApplicationScoped bean and possibly shared by multiple threads.

The documentation says that the MongoCollection is immutable, but it is not clear whether also the other fields/classes it uses internally are thread-safe.

Yes, you can share them. As the documentation for the Immutable annotation states:

Immutable objects are inherently thread-safe; they may be passed between threads or published without synchronization.

Unlike ``MongoClient instances,MongoCollectionandMongoDatabase` instances are lightweight, so while they can be freely shared, it’s cheap to create new ones as needed.

Regards,
Jeff

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.