Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-4156

Connections and threads may stay active after calling `MongoClient.close`

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Open
    • Priority: Minor - P4
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Connection Management
    • Labels:
      None

      Description

      When a MongoClient is closed, it closes the underlying servers, which close underlying connection pools, which close pooled connections. However, because MongoClient is allowed to be used concurrently (true for both synchronous and reactive API), it is possible to have ongoing operations concurrently with calling MongoClient.close. Such connections may be blocked waiting for a response from the server, and may stay not terminated on the client-side until timeout happens or a response is received.

      In other words, MongoClient.close is an asynchronous operation even for a synchronous API, and it does not provide a user with a way to learn when all resources were actually closed (reasoning similar to the one about connections may also be applicable to threads started by the client). A solution from the API standpoint would be to either block MongoClient.close (make it synchronous) until resources are released, or return a CompletableFuture (a composition of Future which allows blocking and CompletionStage, which allows building an asynchronous pipeline). Implementing this does not seem to be trivial1. Maybe we can decide to just document our close methods on public classes that have them with a note that the methods are asynchronous with no way to know when the requested operation completes.

      Internally, this situation causes test logs from different tests to be interlaid with each other even if each test creates a new client and closes it when it ends. It is useful to keep this in mind.


      1 ExecutorService allows waiting until all its threads terminate, but does not allow listening for that. As for connections, we would need to wait until all checked out connections are checked in and then report that the pool is closed. This can be further improved by closing checked out connections in the places where they are used: doing so reduces the time to stop the whole client, but would have to be done in too many places and would significantly complicate the existing code (I do not think this last improvement should ever be done).

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            valentin.kovalenko Valentin Kavalenka
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Dates

              Created:
              Updated: