Should I close JNDI-obtained data source?

浪子不回头ぞ 提交于 2019-12-01 03:58:39
sarcastictrade

I disagree. I would add a listener to your web.xml and implement the contextDestroyed() method. This method will get called by your web container/app server when the web app is destroyed or undeployed. Within the contextDestroyed(), I would close the datasource.

inside the web.xml

<listener>
   <listener-class>util.myApplicationWatcher</listener-class>
</listener>

The code:

package util;

public class myApplicationWatcher implementes ServletContextListener
{
  public void contextInitialized(ServletContextEvent cs)
  {
      // This web application is getting started

      // Initialize connection pool here by running a query
      JdbcTemplate jt = new JdbcTemplate(Dao.getDataSource() );
      jt.queryForInt("Select count(col1) from some_table");
  }

  public void contextDestroyed(ServeletContextEvent ce)
  {
      // This web application is getting undeployed or destroyed 

      // close the connection pool
      Dao.closeDataSource();
  }
}

public class Dao
{
  private static DataSource ds;
  private static bDataSourceInitialized=false;
  private static void initializeDataSource() throws Exception
  {
    InitialContext initial = new InitialContext();

    ds = (DataSource) initial.lookup(TOMCAT_JNDI_NAME);

    if (ds.getConnection() == null)
    {
      throw new RuntimeException("I failed to find the TOMCAT_JNDI_NAME");
    }

    bDataSourceInitialized=true;
  }

  public static void closeDataSource() throws Exception
  {
    // Cast my DataSource class to a c3po connection pool class
    // since c3po is what I use in my context.xml
    ComboPooledDataSource cs = (ComboPooledDatasource) ds;

    // close this connection pool
    cs.close();
  }

  public static DataSource getDataSource() throws Exception
  {
    if (bDataSourceInitialized==false)
    {
      initializeDataSource();
    }

    return(ds);
  }
}

No. The DataSource here is managed by the remote JNDI container, and it's that container's job to manage the lifecycle of the DataSource. Spring just makes use of it, it doesn't manage it.

Even if you wanted to, you couldn't - DataSource has no close() method, or anything like it.

When you get the data source through a JNDI lookup it a shared resource - configured in your container. It is managed by the container and not by the application, so it is not required (there is no way) to close it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!