Ensure proper resource management by clearly defining cleanup responsibilities and implementing robust cleanup patterns. Resources should be closed by their creator, and cleanup must occur even when exceptions happen during resource creation or usage.
Ensure proper resource management by clearly defining cleanup responsibilities and implementing robust cleanup patterns. Resources should be closed by their creator, and cleanup must occur even when exceptions happen during resource creation or usage.
Key principles:
Example pattern:
def fromJDBCConnectionFactory(getConnection: Int => Connection): JDBCDatabaseMetadata = {
var conn: Connection = null
def closeConnection(): Unit = {
try {
if (null != conn) {
conn.close()
}
} catch {
case e: Exception => logWarning("Exception closing connection during metadata fetch", e)
}
}
try {
conn = getConnection(-1) // Resource creation in try block
// ... use connection
} catch {
case NonFatal(e) =>
logWarning("Exception while getting database metadata", e)
// Return default values
} finally {
closeConnection() // Guaranteed cleanup
}
}
This prevents resource leaks and ensures graceful degradation when resource operations fail.
Enter the URL of a public GitHub repository