Anna N
Anna N

Reputation: 21

Spring jdbctemplate close connections upon application shutdown?

I am seeing DB connections not being closed upon application shutdown.

We are using Spring org.springframework.jdbc.core.support.JdbcTemplate, and have configured a connection pool. Example Context xml for Tomcat is this:

<Resource name="jdbc/fooResource"
        auth="Container"
        testOnBorrow="true"
        validationQuery="select 1 from DUAL"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        username="user"
        password="password"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/myschema"
        maxActive="100"
        maxIdle="10"/>

My Spring bean definition has this snippet:

<jee:jndi-lookup id = "dataSource"
     jndi-name = "jdbc/fooResource"
      expected-type = "javax.sql.DataSource"/>

Observations:

  1. MySQL is started up, it shows Connections : 6.
  2. Started up Tomcat with my one web app, and in MySQL, I now see Connections: 16.
  3. Stopped Tomcat and the 16 Connections remain.
  4. I stop/start Tomcat and the Connections just keep climbing (I guess by 10 since initialSize is 10 by default?)

Questions:

  1. I am reading in the docs that using Spring JdbcTemplate takes care of connections (fetching and releasing them to the pool) but what happens on shutdown -- are my connections supposed to be all closed on shutdown?
  2. Am I supposed to do anything else to ensure all DB connections are closed upon application shutdown?

Thanks.

Upvotes: 2

Views: 3565

Answers (1)

Steve Chaloner
Steve Chaloner

Reputation: 8202

If you create the application context manually, you need to register a shutdown hook on the application context. When you start the app, get a reference to the context and add this line

context.registerShutdownHook();

If you don't do this, destruction events aren't triggered.

Upvotes: 2

Related Questions