2

While going through a code I found that all the beans are defined as singleton in a web application. This got me thinking what will happen when multiple threads are trying to access this bean. Will it not degrade the performance?For example , I have a singleton login bean and now there are suppose multiple users trying to login . Now as the bean is singleton then all the users will get the same bean.Will it not degrade the performance? Or is there something else ?

A.Kumar
  • 43
  • 6
  • It's not the bean that does the work, it's the CPU that does the work. If anything it will make things faster because it uses the cpu memory caches more efficiently. However your question is overly broad/vague "Or is there something else" - have a look at the [help]; StackOverflow is not a discussion forum, but a place for clear and specific questions. – Erwin Bolwidt Feb 18 '18 at 02:56
  • Why do you think it degrades performance? You seem to be under the impression that only one thread can use the bean at a time. Why do you think that? I mean, you didn't make the methods `synchronized`, did you? – Andreas Feb 18 '18 at 03:59

2 Answers2

1

Your question has the hint of an answer, because you speak of threads, In general, the code is not "alive", the threads are. As a metaphor, the threads are the ones that are "alive" and "performing", by reading the shared code, which is just there. Threads sharing codeYou could think of the code as writing on a white board, and the threads are doing the work of reading it.

It is different if the shared bean has some state -- say a variable -- that those threads need to change. Extending the metaphor, that's like a number written on the white board which everyone is aloud to change.

Now, one needs some way to make sure the threads do not overwrite each other's work. So, some type of synchronization is needed. The single bean (actually the updatable state inside it) becomes a resource that thread compete for, and one may have to wait for another to complete. That could degrade performance. If not done right, it can also cause errors and deadlocks.

Darius X.
  • 2,886
  • 4
  • 24
  • 51
-1

That has to be taken care by programmer. Because Spring provides different scopes to define creation of beans. More about scopes of spring here.

The way of singleton scope implemented for the bean is different from singleton Design pattern. It's a single bean per spring container. More about spring containers here.

kemparaj565
  • 379
  • 3
  • 6