Make sure the spring component does not have

We faced the issue of multithreading when a developer introduced variability into a Spring component. Something like that:

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

which led to an error in multithreading - access to field intermediate results was available from different threads.

Is there a way to prevent the addition of state in Spring Singleton, for example. some kind of static analyzer? SonarQube plugins? Eclipse plugins? Thanks for the suggestions.

+7
java spring eclipse multithreading
source share
2 answers

MutabilityDetector seems to be able to do exactly what you need:

The Mubility Detector is designed to analyze Java classes and report on whether instances of a given class are immutable. Can be used:

  • In a unit test with an assertImmutable type statement (MyClass.class). Is your class really immutable? How about the change you just made?
  • As a FindBugs plugin. Those classes that you annotated with @Immutable, are they really? At runtime. Does your API require immutable objects? From the command line. Do you want to quickly run the Mubility Detector throughout the code base?

In any case, I would advise adding a clear contract stating that the class should be immutable either through javadoc or via the @Immutable annotation for the class itself, in order to allow (reasonable) developers to maintain the class details. (In case the variability detector cannot detect certain types of immutability, for example: are String, Date immutable? )

+2
source share

You can implement your own rules using any static analyzer (e.g. FindBugs, PMD and Checkstyle) to verify that your class:

  • Permits only final properties
  • Extends a given class
  • Final
  • Uses constructor dependency injection

However, as far as I know, there is no special tool specially tuned for this.

Alternatively, you can create the @Immutable annotation and implement validation there.

+1
source share

All Articles