界: Code Quality

代码质量不佳会导致不可预测的行为。对于用户来说,通常表现为可用性差。对于攻击者来说,提供了以意外方式对系统施加压力的机会。

Code Correctness: Non-Synchronized Method Overrides Synchronized Method

Abstract
不应使用非同步方法覆盖同步方法。
Explanation
父类声明方法 synchronized,以保证当多个线程访问相同实例时的正确行为。应将所有重写方法声明为 synchronized,否则可能会发生意外行为。

例 1:在下列代码中,类 Foo 覆盖类 Bar,但未将方法 synchronizedMethod 声明为 synchronized


public class Bar {
public synchronized void synchronizedMethod() {
for (int i=0; i<10; i++) System.out.print(i);
System.out.println();
}
}

public class Foo extends Bar {
public void synchronizedMethod() {
for (int i=0; i<10; i++) System.out.print(i);
System.out.println();
}
}


这种情况下,Foo 实例会被转换为 Bar 类型。如果将相同的实例交给两个独立线程,并重复执行 synchronizedMethod,则行为将不可预知。
References
[1] Sun Microsystems, Inc. Bug ID: 4294756 Javac should warn if synchronized method is overridden with a non synchronized
[2] TSM00-J. Do not override thread-safe methods with methods that are not thread-safe CERT
desc.structural.java.code_correctness_non_synchronized_method_overrides