Make sure spring component is stateless
We faced a multi-threading problem when a developer introduced mutability to a Spring Component. Something like this:
@Component //singleton
public class MyComponent {
...
private String intermediateResults;
public String businessMethod() {
... fills in intermediateResults;
}
public String thisGetterShouldNotBeHere() {
return intermediateResults;
}
}
which led to bug with multithreading - the field intermediateResults has been accessed from different threads.
Is there are a way to prevent adding state to a Spring Singleton eg by some kind of static analyzer? SonarQube plugins? Eclipse plugins? Thanks for suggestions.
Google's MutabilityDetector seems able to do exactly what you need:
Mutability Detector is designed to analyse Java classes and report on whether instances of a given class are immutable. It can be used:
I would anyway advise to add a clear contract stating that the class is supposed to be immutable either via javadoc
or via @Immutable
annotation on the class itself, to allow (sensible) developers to maintain the class requisites. (In case Google's detector fails to detect specific types of immutability eg: Are String, Date really immutable?)
You could implement your own rules with any static analyzer (Like FindBugs, PMD and Checkstyle) to check that your class:
However, as far as I know, there's no tool specifically configured out of the box for that.
Alternatively you could create an @Immutable
annotation and implement the checks there.
上一篇: 当调用IntPtr构造函数时,Xamarin Android会执行OnCreateView吗?
下一篇: 确保弹簧组件是无状态的