Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a pool of objects, a singleton or static methods in a multi-threaded environment?

I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?

What would be the difference between implementing this class as a singleton and just using static methods?

What would the effect of thousands of users accessing this object/these methods be?

I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.

like image 290
Cris Avatar asked Jul 01 '11 14:07

Cris


People also ask

Which is the best way to implement a singleton pattern for a multi threaded environment in Java 5?

Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. Bill Pugh implementation is most widely used approach for singleton classes.

Which one should I choose static or singleton pattern?

A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .

Why use a singleton instead of static methods?

Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.

Can we use singleton class in multithreading?

While we are using multithreading access to a singleton instance can be performed from various threads it could be a problem while constructing singleton instances. If you are in Singleton::Instance() and receive an interrupt, invoke Singleton::Instance() from another thread, you can see how you'd get into trouble.


1 Answers

Infact instead of singleton you can make the methods static.

Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.

discussion on Singleton vs Static methods is here

like image 107
Manoj Avatar answered Oct 02 '22 19:10

Manoj