0

I know similar questions have been asked but still try to get my head around it. I'm chasing a bug where a database connection does not get closed. Simplified:

class Database {
    private Connection connection;

    Database () {
        connection = connectToDatabase ();
    }

    boolean isConnected () { return connection != null; }

    void disconnect () {
        if (connection != null)
            connection.close ();
    }

    void accessDb () { doSomethingWithDb (); }
}

class Foo
{
    private Database db;

    foo (Database d) {
        db = d;
    }

    void doFoo () {
        if (db.isConnected ())
            db.accessDb ();
    }
}

class Core
{
    Database db;

    private Foo foo;

    Core () {
        db = new Database;
        foo = new Foo (db);
    }

    void serve (String someClientRequest) {
        try {
            foo.doFoo ();
            if (db.isConnected ())
                db.accessDb ();
        } catch (SQLException ignore) {
        }
        finally {
            db.disconnect ();
        }
    }
}

class Servlet
{
    Servlet () {}

    void post (String someClientRequest) {
        Core core = new Core ();
        core.serve (someClientRequest);
    }
}

Maybe the servlet could just call core.db.disconnect () when done (well...could it?), but the actual implementation is more complex. So the question is: will Foo create a new Database connection? Coming from C++, I still find it confusing that objects are said to be "referenced" when in fact they appear to be passed/accesed by value...? Sorry if this has already been covered, I found several answeres on this subject but none would make me understand why that stupid db refuses to close. Thanks!

charlie
  • 68
  • 2
  • 8
  • 1
    [Is Java “pass-by-reference” or “pass-by-value”?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Naman Gala Aug 10 '15 at 11:24
  • 1
    In java all arguments are passed by value and not by reference. Your code seems fine, and maybe the code in the above is not actually the same as your real code. – STaefi Aug 10 '15 at 11:34
  • Thanks, it is in a way, but your hint helped nevertheless. The problem was that one needs to explicitly close resources (Statements, ResultSets),which opens another can of worms altogether...(http://stackoverflow.com/questions/4507440/must-jdbc-resultsets-and-statements-be-closed-separately-although-the-connection) – charlie Aug 10 '15 at 14:21

0 Answers0