Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring bean Handle concurrency

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?

like image 287
Rajeev Akotkar Avatar asked Dec 08 '12 10:12

Rajeev Akotkar


People also ask

How is concurrency handled in Spring?

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.

How does Spring handle concurrent requests?

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.

Does Spring boot handle concurrency?

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.

How does the singleton bean serve the concurrent request?

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.


1 Answers

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.

See also:

  • thread safe, stateless design using Spring
  • spring mvc declaring all beans singleton
like image 85
Tomasz Nurkiewicz Avatar answered Sep 16 '22 11:09

Tomasz Nurkiewicz