Search code examples
javaspring-bootsingletonprototype

Does using singleton pattern will make my application slower if multiple users are working on it simultaneously


I am facing trouble understanding use on Singleton. I understand that while using singleton pattern once one instance of a class is created and is shared across all of the users. However won't this make an application slow for users in multiple (say a few thousands of users) are using that resource at a moment?

For eg. If one of my service class "Sendmail" is a singleton, then only one instance of that class will be created in IOC container. Now this instance will be shared with all of the current users using that resource. Now if multiple users try to send emails at a moment, all of the requests will wait in the queue as only one instance of Sendmail is created, won't this make the users wait to send their email? This will be a very poor experience for the users. Same goes with the Database connection. Then why it is recommended to use Singleton over prototype?

Kindly please help me clear my confusion. Thanks in advance.


Solution

  • No, Singleton pattern does not slow down application. It basically create single object and make it available every time requested.

    But when you are taking about multiple user accessing data/resource at same time this is concurrency concept. if you implement some concurrency control techniques then processing of data/resource might slow down.

    Note : All depends on developer that how horrible code he/she is writing.