3

I was studying the package java.util.concurrent of Java and the following question came to my mind: When using the Spring Framework, should I worry about multi thread scenarios?

For example,I have an API based on Spring Boot. One of my rest services updates an ArrayList. However ArrayList is not thread safe, which could lead to inconsistent data. However, I'm using Spring Framework.

The question is: Do I have to change my current ArrayList to one of the Concurrent Collections of java OR Spring Framework itself is thread-safe and I should not be worried about multi thread scenarios?

Gabriel
  • 952
  • 10
  • 31

2 Answers2

4

Your REST service should be written so it's thread safe. That means no private data members that are mutable. If that's the case, you're safe.

If all your methods use method scope variables, then you're thread safe.

You should know that the app server will spawn a thread for each HTTP request that comes in. If you write the service as if it were single threaded you'll be fine.

You should always worry about multi-thread scenarios.

If your REST service has to interact with a database, then the connection should not be shared. You need a pooled data source that checks out a connection for each request, uses it in method scope, and returns it to the pool. JDBC connections are not thread safe, but you get away with it because you pool them.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

Spring MVC (Spring boot RestServices) is based on Servlet API. The serlets are multithread so you have to take care of concurrency.

But it depends on, how are you programming. If you're variables are class variables/ class members, then you need to take care of concurrency but if your variables are declared inside methods then this is thread-safe.

reos
  • 8,766
  • 6
  • 28
  • 34