Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: IllegalStateException: The pool is closed error message in Spring Boot application

I'm getting this info message:

19-October-24 08:05:53:481 INFO Thread-4 o.m.d.connection:71 - Closed connection [connectionId{localValue:35, serverValue:38}] to mongodb:27017 because the pool has been closed.

And also the following errors:

java.lang.IllegalStateException: The pool is closed at com.mongodb.internal.connection.ConcurrentPool.get(ConcurrentPool.java:137) at

java.lang.IllegalStateException: state should be: open at com.mongodb.assertions.Assertions.isTrue(Assertions.java:70)

This is how I'm creating the MongoClient, plain and simple:

@Bean
@Override
public MongoClient mongoClient() {
    return new MongoClient(host);
}

This SO answer suggests to set socketKeepAlive(true) but as far as I understand this method is deprecated as it's true by default.

  • I'm using MongoTemplate and MongoRepository.
  • The application (as mentioned above) is multi-threaded.

I'd like to understand what's the meaning of the error ? (i.e. Why would the pool ever be closed?).

Do I need to set/adjust some Spring-Boot parameters maybe? Do I need to build MongoClient differently?

like image 556
yaseco Avatar asked Sep 13 '25 09:09

yaseco


1 Answers

This error means your MongoDB connections are closed for some reason and you are trying to use this connection pool.

If you are using springs connection pool you can create your connection pool without spring and you can manage the connection when is closed. ( Like reconnection on errors )

If you are doing multithreaded operations change your MongoClient beans Scope and create it thread based. Mongoclient creates a connection pool in the background and gives already pooled connections to newly created clients so thread-based clients will not create connection on every autowire operation.

If you want to use the socketKeepAlive feature you need to give options like this:

MongoClientOptions options = MongoClientOptions.builder()
                .socketKeepAlive(false)
                .build();

MongoClient mongoClient = new MongoClient( "yourhost:mongoport" ,  options);
like image 73
Burak Akyıldız Avatar answered Sep 16 '25 00:09

Burak Akyıldız