Saturday, November 18, 2017

java.SQl.Sqlexception:Invalid state, the connection object is closed

This exception seems to be wired to you are in suspected mode.Whenever you see this Exception below things comes in your mind
  1. Somebody written bullshit code, Executing query after closing connection object

    what if this is not the case, Then
  2.  If you are using any ORM framework, then might be ORM doing something
    or
  3. if you are using SQL driver, then might driver doing something
Apart from this, there is one more hidden cause which will act secretly on this, if you not aware of that i.e DB Configuration
let's take MSSQl DB for exploring thing

In MSSQL server under TCP connection configuration, there is a property is configured called KEEP ALIVE whose default value is set to 30000 milliseconds.
Let go in depth of KEEP ALIVE behavior, what it does.How database reacts to the time configured under KEEP ALIVE.DB expire the idle connection object if it exceeds the time limit configured under kEEP ALIVE.

How this impact on our application.
In Every application whenever we interact with DB, we will create the connection pool with some minimum count.Let's get in-depth how connection pool will get impacted with KEEP ALIVE property of DB
Let's assume DB connection pool is created with min count 5 and max count 10.While creating connection pool there is one property which is mandatory to know the value of that i.e IdleTime ( name can vary w.r.t driver, ORM ), which say up to what time connection can be idle.Now if IdleTime is more that KEEP ALIVE value and connection Object in the pool is idle more than KEEP ALIVE but less then IdleTime, then the connection object in a pool is getting expired from DB server side and when this connection object is used before IdleTime, you will face  java.SQl.Sqlexception: Invalid state, the connection object is closed.

So be aware while configuring connection pool. All DB connection pool is supposed to configure w.r.t DB configuration and your application activity like :

  • IdleTime should be always lesser than KEEPALIVE
  • If your application is not much-having heavy traffic then min connection should be in small count like 2 or 3
  • Max connection count depends upon how DB accept the connection.