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!