问题描述
根据我的理解,我想遵循最佳实践来最终释放资源,以防止任何连接泄漏。这是我在HelperClass中的代码。
As per my understanding, I want to follow the best practice for releasing the resources at the end to prevent any connection leaks. Here is my code in HelperClass.
public static DynamoDB getDynamoDBConnection()
{
try
{
dynamoDB = new DynamoDB(new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
}
catch(AmazonServiceException ase)
{
//ase.printStackTrace();
slf4jLogger.error(ase.getMessage());
slf4jLogger.error(ase.getStackTrace());
slf4jLogger.error(ase);
}
catch (Exception e)
{
slf4jLogger.error(e);
slf4jLogger.error(e.getStackTrace());
slf4jLogger.error(e.getMessage());
}
finally
{
dynamoDB.shutdown();
}
return dynamoDB;
}
我的疑问是,因为 finally 块会无论如何执行,dynamoDB是否将返回空连接,因为它将在 finally 块中关闭,然后执行 return 语句? TIA。
My doubt is, since the finally block will be executed no matter what, will the dynamoDB returns empty connection because it will be closed in finally block and then execute the return statement? TIA.
推荐答案
您的理解是正确的。 dynamoBD.shutdown()
将始终在返回dynamoDB
之前执行。
Your understanding is correct. dynamoBD.shutdown()
will always execute before return dynamoDB
.
我不熟悉要使用的框架,但是我可能会按以下方式组织代码:
I'm not familiar with the framework you're working with, but I would probably organize the code as follows:
public static DynamoDB getDynamoDBConnection()
throws ApplicationSpecificException {
try {
return new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
} catch(AmazonServiceException ase) {
slf4jLogger.error(ase.getMessage());
slf4jLogger.error(ase.getStackTrace());
slf4jLogger.error(ase);
throw new ApplicationSpecificException("some good message", ase);
}
}
并将其用作
DynamoDB con = null;
try {
con = getDynamoDBConnection();
// Do whatever you need to do with con
} catch (ApplicationSpecificException e) {
// deal with it gracefully
} finally {
if (con != null)
con.shutdown();
}
您还可以创建 AutoCloseable
dynamoDB连接的包装器(在 close
内部调用 shutdown
)并执行
You could also create an AutoCloseable
wrapper for your dynamoDB connection (that calls shutdown
inside close
) and do
try (DynamoDB con = getDynamoDBConnection()) {
// Do whatever you need to do with con
} catch (ApplicationSpecificException e) {
// deal with it gracefully
}
这篇关于在Java中try-catch-finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!