Beans in Spring are singleton by default, and the framework does not encapsulate beans in multiple threads. In fact, beans are stateless most of the time (like DAOs) so they are safe to some extent. But if the Bean is stateful, thread-safety guarantees need to be made by the developer himself, The simplest way to do this is to change the scope of the bean to ‘Protopyte’ instead of ‘singleton’ so that each request to the bean is equivalent to a new bean () so that the thread is safe.

Stateful means data storage. Stateless means no data is stored. For example, defining member variables in a Service is unsafe.

The Controller, Service, and DAO layers themselves are not thread-safe, but if only the methods inside are called, and multiple threads call methods of an instance, they copy variables in memory, which is the working memory of their own threads, and are safe. So as long as you don’t modify the userService instance in userConstroller, that’s fine. Therefore, when calling a method, local variables are enclosed in the thread class, and global variables are not involved in calling a method, so there is no need to worry about thread safety. In general, services are not modified either. To understand how this works, take a look at Understanding JVM Virtual Machines, section 2.2.2:

The Java virtual machine stack is thread-private and has the same lifetime as a thread. The virtual stack describes the memory model of Java method execution: each method execution creates a stack frame to store information about local variables, operand stacks, dynamic links, method exits, and so on.

Section 3.2.2 of Java Concurrent Programming In Action:

One of the inherent properties of local variables is that they are enclosed in the thread of execution. They are located in the stack of the executing thread and cannot be accessed by other threads. So any stateless singleton is actually thread-safe.

Also, it is not thread-safe to modify global service variables in servcie. One thing is, local variables in a method are thread-safe, and member variables outside of a method or all variables, or so-called global caches or whatever, are not thread-safe.