Search code examples
javarecursionrace-condition

Calling Method of another class from Recursion Method: Java


I have two class as A and B-

Class A:- This class has getData method, which is used to get data from DB.

class A {
    public synchronized getData() {
       // get some data from database, in finally block close connection
    }
}

Class B:- Which has recursion method m(), inside this method I am calling the getData() of class A.

class B {
   m() {
      //some condition to terminate the recursion
      A a = new A();
      a.getData();
      m();
   }
}

Error I am getting:-

java.lang.NullPointerException: null at com.mchange.v2.c3p0.impl.NewProxyConnection.getAutoCommit(NewProxyConnection.java:1226) ~[c3p0-0.9.5.1.jar:0.9.5.1]

For the first call of getData() method, I am able to get data from DB, but after second recursion onward I am getting the connection as closed. Any help would be highly appreciated.

Update:

I have DB Util method which is opening the connection each time when getData() method is calling. It's working fine if I am calling this without recursion method(many times) but if I am using recursion I'm getting error. Is any special case I have to handle for recursion method?


Solution

  • The error specifies that connection is closed. Also, in your comment // get some data from database, in finally block close connection, you have mentioned that you have closed the connection after use but, you didn't mentioned that if you are opening the connection in he getData() method or not.

    I would suggest following:

  • Check if you are opening the connection in getData() method. If not then either open the connection in this method only(remove the code for opening connection from some other method) or don't close the connection after use in this method instead use a different method to close the connection as per need.
  • Check if connection resource is reusable.