jdbc connections in clojure are garbage collected prematurely

197 views Asked by At

I am using the [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"] library to connect to a postgres database. The connection is saved inside an atom. I then arm multiple listeners like so:

(doto (.createStatement (connection f))
    (.execute (format "LISTEN %s;" event))
    (.closeOnCompletion)))

f in this case is a function called when the event triggers. For some reason it does not take long until the connection seems to be garbage collected, which obviously makes the listeners non-functioning.

WARNING: Cleaning up leaked connection ( jdbc:pgsql://my-container/database )

This warning is followed by a stacktrace to where I opened the connection in the arm-listeners method.

I tried several things, like store the connection in a let, but none seemed to help with this specific issue.

The complete function to establish the connection and start the listener which I use are those: https://github.com/n2o/postgres-listener/blob/master/src/postgres_listener/core.clj

This is how I start the listeners:

(defn start-listeners
  "Start all important listeners."
  []
  (connect {:host (System/getenv "DB_HOST")
            :port (read-string (System/getenv "DB_PORT"))
            :database (System/getenv "DB_NAME")
            :user (System/getenv "DB_USER")
            :password (System/getenv "DB_PW")})
  (arm-listener handle-textversions "textversions_changes")
  (arm-listener handle-statements "statements_changes")
  (arm-listener handle-arguments "arguments_changes")
1

There are 1 answers

1
WeGi On

It seems that using the connection in a let statement and than returning it, helps the JVM not to collect the reference.

So something like this would help:

(let [conn (connect <...>)
      a (arm-listener f name)]
   conn)

I'll keep the question open for a while, in case somebody has another answer.