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.