Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g. by some kind of static analyzer? SonarQube plugins? Eclipse plugins? Thanks for suggestions.

like image 527
leokom Avatar asked Jan 23 '17 10:01

leokom


People also ask

Are Spring @component singletons?

Yes, that is correct, @Component is a Spring bean and a Singleton. About singletons - spring beans are all in singleton scope by default. The only thing you have to have in mind is that you should not store state in field variables (they should only hold dependencies).

Why singleton beans are stateless?

The only restriction that the Singleton class puts on the JVM is that it can have only one instance of this class in the heap. And this is why ideal singleton bean must be stateless. Otherwise concurrency issues can occur.

How do I disable ComponentScan?

To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

Does @component create a bean?

@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component.


1 Answers

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:

  • 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?

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 Mutability Detector fails to detect specific types of immutability eg: Are String, Date really immutable?)

like image 163
snovelli Avatar answered Oct 23 '22 03:10

snovelli