java - 确保 Spring 组件是无状态的

标签 java eclipse spring multithreading

当开发人员向 Spring 组件引入可变性时,我们遇到了多线程问题。像这样:

@Component //singleton
public class MyComponent {
...
private String intermediateResults;
public String businessMethod() {
 ... fills in intermediateResults;
}

public String thisGetterShouldNotBeHere() {
    return intermediateResults;
 }
}

这导致多线程错误 - 字段 intermediateResults 已从不同的线程访问。

是否有一种方法可以防止向 Spring Singleton 添加状态,例如通过某种静态分析仪? SonarQube 插件? eclipse 插件? 感谢您的建议。

最佳答案

MutabilityDetector似乎能够完全满足您的需求:

Mutability Detector is designed to analyse Java classes and report on whether instances of a given class are immutable. It can be used:

  • In a unit test, with an assertion like assertImmutable(MyClass.class). Is your class actually immutable? What about after that change you just made?
  • As a FindBugs plugin. Those classes you annotated with @Immutable, are they actually? At runtime. Does your API require being given immutable objects? From the command line. Do you want to quickly run Mutability Detector over an entire code base?

无论如何,我会建议添加一个明确的契约(Contract),说明该类应该是不可变的,可以通过 javadoc 或通过类本身的 @Immutable 注释,以允许(明智的)开发人员维护类的必要条件。 (以防 Mutability Detector 无法检测到特定类型的不可变性,例如:Are String, Date really immutable?)

关于java - 确保 Spring 组件是无状态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41803680/

相关文章:

java - Spring Roo : Deleting from DB?

java - 如果 AppContext 初始化失败,正确终止 Spring Boot 和 Tomcat

java - Eclipse会忽略条件断点(java for hadoop)

java - 长度超过 65535 字节的 Java 字符串文字的字节码

java - TextView 数组不起作用?

java - Eclipse 生成 getter 和 setter 并自动应用它们

java - 从 Spring MVC Controller 推送实时数据

java - 如何使我的 Java Web 应用程序在根 URL 上可用?

java - Android NFC Intent 不是 "called"

java - Eclipse : Cannot get a DefaultScreenDevice -> cannot launch any GUI 中的问题