最近使用到sonarQube代码检测工具,特此总结一些常见问题,以便查阅、回忆,提升代码质量。
1. “wait(…)” should be used instead of “Thread.sleep(…)” when a lock is held 持有锁时应该使用wait而不是sleep
If Thread.sleep(…) is called when the current thread holds a lock, it could lead to performance and scalability issues, or even worse to deadlocks because the execution of the thread holding the lock is frozen. It’s better to call wait(…) on the monitor object to temporarily release the lock and allow other threads to run.
Thread.sleep并不会释放锁,可能导致死锁、阻塞
// Noncompliant Code Example
public void hello(){
synchronized(monitor) {
while(true){
Thread.sleep(200);
}
process();
}
}
// Compliant Solution
public void Hello(){
synchronized(monitor) {
while(true){
monitor.wait(200);
}
process();
}
...
}
See
- CERT, LCK09-J.Do not perform operations that can block while holding a lock
2. Define a constant instead of duplicating this literal “Hello” 10 times.定义常量来代替重复出现的字符串
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
重构过程容易出错,因为必须确保更新所有的地方。
只占用一个String内存
Code Example
// Noncompliant - "action1" is duplicated 3 times
public void run() {
prepare("Hello");
execute("Hello");
release("Hello");
}
private static final String HELLO= "Hello"; // Compliant
public void run() {
prepare(HELLO); // Compliant
execute(HELLO);
release(HELLO);
}
3. Inject this field value directly into method parameter, the only method that uses it.直接使用@bean装饰方法中的入参注入
When @Autowired is used, dependencies need to be resolved when the class is instantiated, which may cause early initialization of beans or lead the context to look in places it shouldn’t to find the bean. To avoid this tricky issue and optimize the way the context loads, dependencies should be requested as late as possible. That means using parameter injection instead of field injection for dependencies that are only used in a single @Bean method.
使用@Autowired时依赖很可能被提前初始化,或者产生依赖问题。依赖应当越晚初始/注入越好。
将仅有一个引用的依赖放入@Bean修饰方法的入参中。
Code Example
@Configuration
public class Example {
@Autowired private MySource mySource; // Noncompliant
@Bean
public Example myMethod() {
return new Example(this.dataSource);
}
}
@Configuration
public class Example {
@Bean
public Example myMethod(MySource mySource) { // Compliant
return new Example(dataSource);
}
}
持续更新中-----