My question relates to the release of mysql connections from within node.
If I return before the connection is released, will that connection still be held or will garbage collection deal with that for me?
The reason I ask is, I did have a problem once upon a time where subsequent connections were refused as I had used my entire connection pool without releasing them.
The problem does not seem to occur doing this, so I just wanted some clarification if possible.
Thanks in advance.
Grant.
sql.getConnection(function (err, connection) {
if (err) {
res.send(4xx,"error");
return;
}
if (req.body.premium) {
//try premium first
//code snipped
return;
}
//code snipped
connection.release();
});
It is unlikely that database connections are even subject to garbage collection in javascript since that requires fairly low level integration into the JS engine.
That aside, as long as your callback you passed to .getConnection()
has not yet been called, the closure created in your code is still alive and none of the variables inside that closure will be garbage collected even though you have returned from the original function call. This is an important feature of javascript when using asynchronous operations and is widely used in asynchronous programming.
It does appear that you have multiple code paths that will not release the connection though since you have two return
statements before the call to connection.release();
so both of those paths look to me like a way through your code where you would not release the connection properly (this has nothing to do with garbage collection).
If you are failing to release the connection, then it will not be available in the pool and cannot be used by other callers and you could run out of pooled connections.
Garbage collection will not solve this issue for you. You will HAVE to make sure that all code paths release the connection when you are done with it. Otherwise, you will "leak" connections and your connection pool will end up out of connections.