My web application uses Spring IOC. So all my spring beans will be singletons by default. In case if two requests try to access two different methods of a single class (for example MySpringBean
is a class which has two methods searchRecord
and insertRecord
) at the same time, both the requests will access the same spring bean concurrently.
How does the same spring bean be available to both the clients at the same time or is it going to be concurrency problem when both the requests will try to access two different methods but through the same spring bean. And since spring bean is a singleton so new instance can not be formed. In this case how is this going to work?
In Spring, every request will be created in a separate thread. for example, they can be called "searchRecord" thread and "insertRecord" thread. both of them will find the same object in the heap, but each thread creates its own stack of execution.
The Java heap, as we know, is a globally shared memory accessible to all the running threads within an application. When the Spring container creates a bean with the singleton scope, the bean is stored in the heap. This way, all the concurrent threads are able to point to the same bean instance.
The Spring Framework provides abstractions for asynchronous execution of tasks by using the TaskExecutor interface. Executors are the Java™ SE name for the concept of thread pools. Spring's TaskExecutor interface is identical to the java.
For concurrent request, single bean will serve for mutliple requests one by one. If the singleton bean will serve concurrent request one by one means, Then why we are we going synchronization because the request will get process one by one.
You must first understand when concurrency can cause problems. If your Spring bean is stateless (it doesn't have any fields, all fields are final
or all of them are assigned only once), multiple threads can safely use the same bean, or even the same method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With