Rajeev Akotkar
Rajeev Akotkar

Reputation: 1397

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?

Upvotes: 29

Views: 33252

Answers (5)

Andrew
Andrew

Reputation: 876

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.

Upvotes: 0

Mohamed Salihu
Mohamed Salihu

Reputation: 1

Java singleton and spring singleton are different. Spring singleton scope will be available within context.

Java singleton scope will be in JVM class loader. Hence concurrent request possible only through spring contexts

Upvotes: 0

Raghuram
Raghuram

Reputation: 371

As others have already suggested, Spring is going to provide the same instance to all the threads in case of "singleton" beans.

What you need to understand is that threads do all the work in a system by executing the code while objects provide state and behavior (code). So it is indeed possible for multiple threads (requests in your case), to be concurrently running same methods in a singleton bean. You can either make such beans stateless as Tomasz suggested or otherwise make them "thread-safe".

Upvotes: 6

hertzsprung
hertzsprung

Reputation: 9893

If the bean is a singleton, then Spring will give you the same instance in any thread. It's up to you to make that bean thread-safe. Since it's a singleton, you'd be best off making that class stateless.

Upvotes: 7

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

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:

Upvotes: 16

Related Questions