0

I have a JSP/Servlet based application, the database team is complaining about the increase in open database connection.I suspect that the connection is not closed after use.

I want to make some code changes by initializing the connection string in try catch block as suggested in Java 8

I have tried closing the connection in final block which is working fine

here is the code i want to implement , Will this fix the issue?Is there any other way to close the open connections after use with little code change?

   try(Connection con =  DBConnectivity.openConnectionThread(); 
   PreparedStatement ps1 = con.prepareStatement(sql1)) {
   -----
     ------
    }
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
BipinSasi
  • 187
  • 14
  • Is this *THE ONLY PLACE* in your code that you access database? You don't use db in other part of the application? – zaerymoghaddam Jul 18 '19 at 08:44
  • Possible duplicate of [Try / Try-with-resources and Connection, Statement and ResultSet closing](https://stackoverflow.com/questions/22671697/try-try-with-resources-and-connection-statement-and-resultset-closing) – Rowi Jul 18 '19 at 08:47
  • No there are multiple places where the connection is initialized. I am using Connection Pooling public static final ThreadLocal connectionThread = new ThreadLocal(); – BipinSasi Jul 18 '19 at 12:14
  • @BipinSasi That is not a proper way of connection pooling, and can easily leak connections. – Mark Rotteveel Jul 18 '19 at 17:22

1 Answers1

1

You should close also PreparedStatement

try(Connection con =  DBConnectivity.openConnectionThread();
     PreparedStatement ps1 = con.prepareStatement(sql1)) 
    {
   -----
     ------
    }
Ori Marko
  • 56,308
  • 23
  • 131
  • 233