'should I close the Singleton DB connection object inside AWS lambda?
I've a plain simple aws lambda written in java(No framework involved). Currently, I've used a Singleton instance for DBConnection as I wanted to re-use the earlier DBconnection object as long as lambda is warm. Also, the best practice suggests writing code outside the handler for efficient reuse and reducing runtime. I wanted to use the same DB connection again. But I've observed that the connection is being closed every invocation of lambda so it defies the Singleton purpose. To address that, I'm not closing the created connection. (By Default it was getting closed due to Autocloseable behavior I got rid of that now.) The Singleton class for connection is below:
public enum DatabaseConnection {
INSTANCE;
static Connection CONNECTION = null;
static String url = "jdbc:URL";
static String user = "user";
static String pass = "pwd";
static
{
try {
CONNECTION = DriverManager.getConnection(url, user, pass);
}
catch (SQLException e) {
}
}
public Connection getConnection(LambdaLogger logger) throws SQLException
{
if(CONNECTION == null || CONNECTION.isClosed()) {
CONNECTION = DriverManager.getConnection(url, user, pass);
}
return CONNECTION;
}
}
My question is:
- Is there any repercussions on the server-side if I don't close the connection in the client?
- Should I need not worry as lambda invocation runs in a separate JVM itself and if the JVM shuts down, anyway the connection object is GCed?
The idea is to reuse the DB connection object in AWS lambda without any framework.
Solution 1:[1]
- Is there any repercussions on the server-side if I don't close the connection in the client?
There should not be any repercussions. AWS Lambda functions create containers and resources to execute your code. When your Lambda function finishes executing, background processes that are still running will be reused the next time the lambda is called. However, it is not guaranteed that AWS will reuse the same container. So initialization could actually happen.
You can read about The Freeze/Thaw Cycle in Lambda functions here.
- Should I need not worry as lambda invocation runs in a separate JVM itself and if the JVM shuts down, anyway the connection object is GCed?
If the JVM shuts down, Garbage Collection will close any open stream. If for some reason the JVM does not close the connection, the OS will take care of it. This does not ensure that it will be appropriately dealt with, but at this point, it's up to the OS how processes and resources are managed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | chris |