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

Optimize singleton code

jatan bhavsar
Ranch Hand

Joined: Jul 23, 2008
Posts: 296

Hi Ranchers,

How can i optimize the creation of singleton object?



Specially when i dont want to check if the singletonExample is null or not
singletonExample == null
condition in my code and want to create singleton object.
Regards
Jatan
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14274
    
  21

You could just create the instance immediately when the class is loaded, in line 3. So, instead of = null you'd write = new SingletonExample(). In the getInstance() method you'd then only have to return the instance.

Your current version is also not thread-safe. It's possible that two threads would call getInstance() at the same time, and two instances of the class are created.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8016
    
  22

jatan bhavsar wrote:How can i optimize the creation of singleton object?

Answer: In 99.99999% of cases:
private static SingletonExample singletonExample = new SingletonExample();

And if it takes so long to create an instance that direct instantiation is out of the question:
1. Check your design.
2. Work out if you really, really need a singleton.
3. Find another line of work.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
Another solution (suggested by Joshua Block in the book "Effective Java"):

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

jatan bhavsar wrote:Specially when i dont want to check if the singletonExample is null or not


In addition to what Jesper, Winston and D. Ogranos said (which I completely agree with) - are you really worried about the time taken to check if it's null or not? If that's remotely significant then you have much bigger problems anyway.
jatan bhavsar
Ranch Hand

Joined: Jul 23, 2008
Posts: 296

Hi All,

This question was asked in interview? How can i create singleton object keeping everything same as written in the code expect the null condition.

Regards
Jatan
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Why didn’t you say it was an interview question? Interview questions and real life are totally different.
In an interview you should have talked about the benefits or otherwise of singletons. About double‑checked locking, and whether it works or not. About whether you synchronise access to that method. About whether it is possible at all. About whether they think it is possible. About whether the interviewer knows anything about singletons, or whether you are desperate enough for a job to work there at all
jatan bhavsar
Ranch Hand

Joined: Jul 23, 2008
Posts: 296

Hi Campbell,

He said it is possible, everything else we discussed .

I tried but couldn't get the answer for this. So i came to Ranchers.

Regards
Jatan
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

It's possible he was looking for this solution, which does allow safe lazy-initialization of a singleton in Java without any null checks (using a trick with inner classes).

Singleton_pattern#The_solution_of_Bill_Pugh

But I'd still prefer creating it up front in the vast majority of cases.
jatan bhavsar
Ranch Hand

Joined: Jul 23, 2008
Posts: 296

Hi Matthew,

Thank you for the answer. This is the thing which he was looking for But i also missed it.


Regards
Jatan
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Matthew Brown wrote:
But I'd still prefer creating it up front in the vast majority of cases.


There is in fact never a reason to lazily instantiate a singleton. The correct way to handle it is to just instantiate it at declaration. (Or, if you prefer the more modern approach, the 1-element enum shown earlier, though I personally still feel itchy when I see that.)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
There is a Richard Gordon story about two examiners for a postgraduate medical diploma; one could feel the spleen and the other couldn’t. Both on the same patient. The candidates had a 50/50 chance of passing, depending on whether they could feel the spleen and on who examined them.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Jeff Verdegan wrote:
Matthew Brown wrote:
But I'd still prefer creating it up front in the vast majority of cases.


There is in fact never a reason to lazily instantiate a singleton. The correct way to handle it is to just instantiate it at declaration. (Or, if you prefer the more modern approach, the 1-element enum shown earlier, though I personally still feel itchy when I see that.)

Sounds dangerously absolutist; I can't agree with that at all. Especially when stated as a "fact". Matthew has a perfectly sensible attitude about it.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Mike Simmons wrote:
Jeff Verdegan wrote:
Matthew Brown wrote:
But I'd still prefer creating it up front in the vast majority of cases.


There is in fact never a reason to lazily instantiate a singleton. The correct way to handle it is to just instantiate it at declaration. (Or, if you prefer the more modern approach, the 1-element enum shown earlier, though I personally still feel itchy when I see that.)

Sounds dangerously absolutist; I can't agree with that at all. Especially when stated as a "fact". Matthew has a perfectly sensible attitude about it.


I'm generally of the "never say never" anti-absolutist mindset as well. But I'm not an absolutist about it.

I have detailed in at least one other thread here (or possibly on Oracle's forums, but I think here) exactly why there's never a need for lazy instantiation of a singleton. If you're interested, you may be able to find it by searching for my name + singleton, although there will probably be a lot of threads that match. I even included the only situation in which it would be beneficial, and pointed out that I believe that to only arise as a result of a design flaw in the first place.

If you know of an occasion where it makes sense, I'd love to see it, and will gladly preface my "never" with a parenthesized "(almost)". Until then, I'll stick with the absolute view.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
I searched a bit and found places where you made the assertion. Didn't see much to back it up - but I don't claim to have done a thorough search. If there's one in particular you'd like to point out, I'm happy to take a look.

On the other hand, you do seem to grudgingly accept the 1-element enum approach, which is a lazily-instantiated singleton. And you acknowledge that there is at least one exception somewhere to your rule. So I'm not sure what you really object to here.

For myself, I would consider lazy singleton initialization when

(a) I need a singleton (this is the rarest part of the requirement)
(b) It may take some time or other resources to initialize, and
(c) some/many users will never even need it

As an example, let's say I'm making a MathUtils library and want to include some methods to provide lists of prime numbers for things like factoring. I expect to keep an array of all primes from 2 to N cached in memory, and beyond N maybe read from a file, or calculate on the fly, or some combination of those. Now there's really no reason to have more than one of these in memory anywhere - the list of prime numbers is the same for everyone. But many users of my MathUtils library will never call the methods that rely on primes (we're assuming I have other nifty features to offer). Why should they wait around for that array of primes to get loaded? And why should they need to put up with the JVM memory being taken up by data they don't need? Seems to me like a prime candidate (pun unintended, sorry) for a lazy singleton.

I'm sure there are a variety of ways to implement this that might not fit a suitably narrow definition of singleton. Using statics everywhere comes to mind - but that tends to make it difficult to mock out this component when testing other stuff. And anyway, as a grown-up programmer who has read both editions of Effective Java, I have no problem making a working thread-safe lazy-initialized singleton using several possible techniques. What's wrong with using the tools at my disposal, if I know what I'm doing?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Mike Simmons wrote:I searched a bit and found places where you made the assertion. Didn't see much to back it up - but I don't claim to have done a thorough search. If there's one in particular you'd like to point out, I'm happy to take a look.


No worries. I know it's out there, but I'm too lazy to hunt it down.

On the other hand, you do seem to grudgingly accept the 1-element enum approach, which is a lazily-instantiated singleton.


I grudgingly accept it in spite of, or perhaps without regard to the fact that it's lazily instantiated, certainly not because of it.

And you acknowledge that there is at least one exception somewhere to your rule.


But as I stated, that case only comes as a result of crappy design to start with. So fix the design.

For myself, I would consider lazy singleton initialization when

(a) I need a singleton (this is the rarest part of the requirement)
(b) It may take some time or other resources to initialize, and
(c) some/many users will never even need it


Okay, here's the meat of my argument I mentioned previously:

1. A singleton being particularly heinous to instantiate is very rare.

2. The class won't be loaded until you go to use it. (I remember seeing or participating in a discussion a few years ago on another forum that debated whether lazy class loading was required by the JVM spec. I think it turned out that lazy loading is not, but lazy initializing is, and it's the initialization step that would be instantiating an eager singleton. Even if that is allowed to not be lazy, I'm willing to bet that it's a rare JVM that will eagerly initialize a class.)

3. The only way you're going to incur a large but avoidable overhead that would lead to meaningful benefit from lazy instantiation is if A) You have that very rare, expensive to init singleton, AND either B1) Your JVM loads the class before you use it OR B2) You're using some other methods of the class that don't require the instance to be created AND you're not going to be using the instance-dependent methods shortly thereafter.

Now, if you're using methods of a singleton that don't require the instance, that's bad enough design right there. And even if you do that, if you're going to use the instance-dependent methods shortly after, there's no benefit to lazy instantiation, and if you don't use them, then your design is doubled-borked. You've got one class doing too many disparate jobs.

So, I maintain that there is no real-world use case where there is meaningful benefit to lazily instantiating a singleton in Java.


As an example, let's say I'm making a MathUtils library and want to include some methods to provide lists of prime numbers for things like factoring. I expect to keep an array of all primes from 2 to N cached in memory, and beyond N maybe read from a file, or calculate on the fly, or some combination of those. Now there's really no reason to have more than one of these in memory anywhere - the list of prime numbers is the same for everyone. But many users of my MathUtils library will never call the methods that rely on primes (we're assuming I have other nifty features to offer). Why should they wait around for that array of primes to get loaded?


I can see calculating the primes lazily. I can't see why that would lead to lazily instantiating a singleton.

I'm sure there are a variety of ways to implement this that might not fit a suitably narrow definition of singleton. Using statics everywhere comes to mind - but that tends to make it difficult to mock out this component when testing other stuff. And anyway, as a grown-up programmer who has read both editions of Effective Java, I have no problem making a working thread-safe lazy-initialized singleton using several possible techniques. What's wrong with using the tools at my disposal, if I know what I'm doing?


I'm not saying lazy instantiation of a singleton is going to bring about the end of civilization as we know it. I'm merely asserting that there's no meaningful benefit to it.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8016
    
  22

Jeff Verdegan wrote:I'm not saying lazy instantiation of a singleton is going to bring about the end of civilization as we know it. I'm merely asserting that there's no meaningful benefit to it.

One possibility that occurred to me was something that is time-critical. Setting aside all the arguments about whether or not you should actually have singletons at all, suppose I have one that needs to be initialized with the latest available data - I don't know, maybe a stock market quotation or something. Once set-up, we're happy to work with what we've got; but we would like the latest available data at the time the object is first used.

Wouldn't that constitute a candidate for lazy instantiation?

Winston
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Winston Gutkowski wrote:[suppose I have one that needs to be initialized with the latest available data - I don't know, maybe a stock market quotation or something. Once set-up, we're happy to work with what we've got; but we would like the latest available data at the time the object is first used.

Wouldn't that constitute a candidate for lazy instantiation?


Not at all. The class doesn't get loaded/initialized until you use it, so, at the moment you first use it, eager instantiation initializes the instance with the latest data.


 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Optimize singleton code