• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Optimize singleton code

 
Ranch Hand
Posts: 300
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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

 
Ranch Hand
Posts: 214
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another solution (suggested by Joshua Block in the book "Effective Java"):

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 300
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Marshal
Posts: 79178
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 300
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 300
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Matthew,

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


Regards
Jatan
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.


 
So there I was, trapped in the jungle. And at the last minute, I was saved by this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic