aspose file tools*
The moose likes Performance and the fly likes Singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Singleton pattern" Watch "Singleton pattern" New topic
Author

Singleton pattern

ravisha andar
Ranch Hand

Joined: Feb 25, 2011
Posts: 55
Hi All,

Can anybody please let me know what is the advantage of singleton pattern and in what scenario it can be used?


Suppose i create a singleton for the database connection object : What will happen if 15000 users login simultaneously ?



Please help me with this?

Thanks
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

Why would you do something like that? You don't think you can have multiple connections?

Anyway, forget about singletons. You almost never have a good reason to use them. Only when dependency injection becomes incredibly cumbersome and doesn't add much flexibility. A good example is a logger.

Loggers should be available to the entire application, so it's cumbersome to use dependency injection. Also, loggers are fairly safe to use. If you use the same logger by multiple classes concurrently, and something goes wrong, it probably won't break your code, because loggers are not essential to the operation of your program. Information only goes one way, from your program to your logger.

If the information goes from the singleton candidate to the program, make it read only. An example is configuration settings, encapsulated in a single class. This may be considered a poor example, because configuration settings should probably be broken up and passed as arguments to the classes that need them. Read-only configuration settings are also not very flexible, because they require you to restart a program when you want new settings to take effect.

So really, singletons have *very* limited use.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4658
    
    5

ravisha andar wrote: Can anybody please let me know what is the advantage of singleton pattern and in what scenario it can be used?

The only advantage of the singleton pattern is that it was documented in the Gang of Four book, and everyone understands it.

Singletons Considered Harmful.

Don't use them. There is a long list of why they are the most over rated pattern in all of Java programming.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

What do you do for logging, Pat?
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4658
    
    5

Stephan van Hulst wrote:What do you do for logging, Pat?

Apache's Log4j

I don't have to unit test it. but it does have bugs. And I get NPEs from it on occasion.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Singleton pattern