Sonar asks to quot;Use try-with-resources or close this quot;Connectionquot; in a quot;finallyquot; clause.quot;(Sonar 要求“使用 try-with-resources 或关闭此“连接.在“终于中条款.)
问题描述
我想要一个干净的项目.所以我用 Sonar 来检测潜在的缺陷,...
I want to have a clean project. So I used Sonar to detect potential defects, ...
在以下方法中,Sonar 要求:使用 try-with-resources 或在finally"子句中关闭此连接".
.
On the below method, Sonar asks to : Use try-with-resources or close this "Connection" in a "finally" clause.
.
private Connection createConnection() throws JMSException {
MQConnectionFactory mqCF = new MQConnectionFactory();
...
Connection connection = mqCF.createConnection(...);
connection.start();
return connection;
}
你能解释一下我做错了什么以及如何避免声纳消息吗?谢谢.
Can you explain me what I did wrong and how to do to avoid Sonar message? Thank you.
推荐答案
在java中,如果你使用FileInptStream, Connection, ResultSet, Input/OutputStream, BufferedReader, PrintWriter等资源
你必须关闭它在垃圾收集发生之前.所以基本上每当连接对象不再使用时,您都必须关闭它.
In java if you are using resource like FileInptStream, Connection, ResultSet, Input/OutputStream, BufferedReader, PrintWriter
you have to close it before garbage collection happens.
so basically whenever connection object no longer in use you have to close it.
试试下面的片段
Connection c = null;
try {
c = mqCF.createConnection(...);
// do something
} catch(SomeException e) {
// log exception
} finally {
try {
c.close();
} catch(IOException e1){
// log something else
}
}
//try-with-resources
try(Connection connection = mqCF.createConnection(...)) {
//use connection here
}
在try with resource的情况下连接会被jvm自动关闭,但是Connection接口必须扩展成AutoCloseable/Closable
接口.
In the try with resource case connection will automatically close by jvm, but Connection interface must be extends with AutoCloseable / Closable
interface.
这篇关于Sonar 要求“使用 try-with-resources 或关闭此“连接".在“终于"中条款."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sonar 要求“使用 try-with-resources 或关闭此“连接".在“终于"中条款."
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01