Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton And Exceptions Question

 
Chris Heady
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I don't often use the normal lazy instantiation singleton implementation of:

I don't use it because of their is no way of guaranteeing that there will only be one because of synchronization issues (doubly checked locking). I use:

However, this piece of code comes into trouble if my constructor throws exceptions. It won't compile because you cant throw exceptions in the initializer area. Say the first time it is used I need to make an db call, and I want the user of the singleton to handle the exception so I can't handle it in the constructor. Any ideas?
[ June 21, 2002: Message edited by: Chris Heady ]
[ June 21, 2002: Message edited by: Chris Heady ]
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, first i think you did a typo and you should have the Singelton self instances as static also.
secondly, why not just make the static getInstance() method synchronized...? wont that solve your problems?
 
Chris Heady
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Roy Ben Ami:
well, first i think you did a typo and you should have the Singelton self instances as static also.
secondly, why not just make the static getInstance() method synchronized...? wont that solve your problems?

You are right that the selves should be static. If you make the getInstance synchronized, then you would slow down performance heavily since many classes will most likely be using the getInstance method. The way that gets you lazy instantiation and quick access if the servlet has already been created is Double Checked Locking(DCL):

But that has problems as demonstrated in this article: DCL javaworld article
[ June 21, 2002: Message edited by: Chris Heady ]
 
Fritz Passow
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, this piece of code comes into trouble if my constructor throws exceptions. It won't compile because you cant throw exceptions in the initializer area. Say the first time it is used I need to make an db call, and I want the user of the singleton to handle the exception so I can't handle it in the constructor. Any ideas?

You could catch and save the exception, then re-throw it from getInstance().
 
Chris Heady
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ahh, your right, I can save it as a member variable, and then check to see if it is not null and throw the exception in the getInstance method. Thanks very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic