阻断
1、“PreparedStatement” and “ResultSet” methods should be called with valid indices
PreparedStatement 与 ResultSet 参数设置与获取数据由序号 1 开始而非 0。
PreparedStatement ps = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?");
ps.setDate(0, date); // Noncompliant
ps.setDouble(3, salary); // Noncompliant
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String fname = rs.getString(0); // Noncompliant
// ...
}
2、 “wait” should not be called when multiple locks are held
wait() 方法不应该在多重锁内被使用,此时线程只释放了内层锁,而没有释放外层锁,可能导致死锁。
synchronized (this.mon1) {
// threadB can't enter this block to request this.mon2 lock & release threadA
synchronized (this.mon2) {
this.mon2.wait(); // Noncompliant; threadA is stuck here holding lock on this.mon1
}
}
3、“wait(…)” should be used instead of “Thread.sleep(…)” when a lock is held
当持有锁的当前线程调用 Thread.sleep (…) 时,可能导致死锁问题。因为被挂起的线程一直持有锁。合适的做法是调用锁对象的 wait () 释放锁让其它等待线程运行。
public void doSomething(){
synchronized(monitor) {
while(notReady()){
Thread.sleep(200);
}
process();
}
...
}
应:
public void doSomething(){
synchronized(monitor) {
while(notReady()){
monitor.wait(200);
}
process();
}
...
}
4、Double-checked locking should not be used
单例懒汉模式:当变量没加 volatile 修饰时,不要使用双重检查
public class DoubleCheckedLocking {
private static Resource resource;
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
static class Resource {
}
}
应
public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
static class Resource {
}
}
5、Loops should not be infinit
不应该存在死循环。
int j;
while (true) {
// Noncompliant; end condition omitted
j++;
}
6、Methods “wait(…)”, “notify()” and “notifyAll()” should not be called on Thread instances
不应该调用线程实例的 “wait (…)”, “notify ()” and “notifyAll ()”。
Thread myThread = new Thread(new RunnableJob());
...
myThread.wait(2000);
7、Printf-style format strings should not lead to unexpected behavior at runtime
因为 Printf 风格格式化是在运行期解读,而不是在编译期检验,所以会存在风险。
String.format("Not enough arguments %d and %d", 1); //Noncompliant; the second argument is missing
String.format("The value of my integer is %d", "Hello World"); // Noncompliant; an 'int' is expected rather than a String
String.format("Duke's Birthday year is %tX", c); //Noncompliant; X is not a supported time conversion character
String.format("Display %0$d and then %d", 1); //Noncompliant; arguments are numbered starting from 1
String.format("%< is equals to %d", 2); //Noncompliant; the argument index '<' refers to the previous format specifier but there isn't one
8、Resources should be closed
打开的资源应该关闭并且放到 finally 块中进行关闭。可以使用 JDK7 的 try-with-resources 表达式
private void readTheFile() throws IOException {
Path path = Paths.get(this.fileName);
BufferedReader reader = Files.newBufferedReader(path, this.charset);
// ...
reader.close(); // Noncompliant
// ...
Files.lines("input.txt").forEach(System.out::println); // Noncompliant: The stream needs to be closed
}
private void doSomething() {
OutputStream stream = null;
try {
for (String property : propertyList) {
stream = new FileOutputStream("myfile.txt"); // Noncompliant
// ...
}
} catch (Exception e) {
// ...
} finally {
stream.close(); // Multiple streams were opened. Only the last is closed.
}
}
严重
标记1、“runFinalizersOnExit” should not be called
默认情况 JVM 退出时是不运行 finalizers 的,System.runFinalizersOnExit 和 Runtime.runFinalizersOnExit 可以在 jvm 退出时运行,但是因为他们不安全而弃用。
public static void main(String [] args) {
...
System.runFinalizersOnExit(true); // Noncompliant
}
protected void finalize(){
doSomething();
}
应:
Runtime.addShutdownHook(new Runnable() {
public void run(){
doSomething();
}
});
2、“ScheduledThreadPoolExecutor” should not have 0 core threads
java.util.concurrent.ScheduledThreadPoolExecutor 由 corePoolSize 指定核心线程数,如果设置为 0 表示线程池无线程可用且不做任何事。
3、 “super.finalize()” should be called at the end of “Object.finalize()” implementations
protected void finalize() {
releaseSomeResources();
super.finalize (); // 调用,最后调用
}
4、Dependencies should not have “system” scope
maven 依赖不应该有 system 类型的依赖范围,使得系统的可移植性低。
<dependency>
<groupId>javax.sql</groupId>
<artifactId>jdbc-stdext</artifactId>
<version>2.0</version>
<scope>system</scope> <!-- Noncompliant -->
<systemPath>/usr/bin/lib/rt.jar</systemPath> <!-- remove this -->
</dependency>
5、Locks should be released
保证锁能够被释放
public class MyClass {
private Lock lock = new Lock();
public void doSomething() {
lock.lock(); // Noncompliant
if (isInitialized()) {
// ...
lock.unlock();
}
}
}
应:
public class MyClass {
private Lock lock = new Lock();
public void doSomething() {
if (isInitialized()) {
lock.lock();
// ...
lock.unlock();
}
}
}
标记6、The signature of “finalize()” should match that of "Object.finalize()"
普通方法不应该以 finalize 命名。以免和 Object.finalize() 方法混淆。
public int finalize(int someParameter) {
// Noncompliant
/* ... */
}
应:
public int someBetterName(int someParameter) {
// Compliant
/* ... */
}
7、Zero should not be a possible denominator
分母不应该为零