Results 1 to 3 of 3
  1. #1
    ribo916 is offline Member
    Join Date
    Sep 2013
    Rep Power

    Default Singleton eager instantiation versus lazy

    Most articles recommend lazy instantiation in Singletons. Unfortunately, lazy instantiation puts you at risk of threading issues (and having to use a double deadlock solution to ensure your design pattern).

    Per the Internet (which is never wrong).
    * The GoF book on design patterns references using lazy instantiation, so most Java developers use this… BUT
    * GoF used lazy instantiation because C++ cannot guarantee the order of static initialization at runtime

    Java does not have this problem. The first call to MySingleton.getInstance() will force the runtime to load the class MySingleton, and since your instance is static it will be initialized just after the class is loaded

    Seems to me that we should be using eager instantiation for Singletons in Java because there is no need to do lazy instantiation of Singletons. The only reason otherwise is if you really only want to create that 1 object on first call for some specific memory saving reason.


    Agreed or is this article by javaworld missing some key information that may prove why lazy instantiation should abosolutely be used?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Rep Power

    Default Re: Singleton eager instantiation versus lazy

    I have never used lazy instantiation for pretty much the reason you state.
    Unless the class has other static methods then you gain nothing...and I cannot think of the last time I needed to write a singleton with other static methods than getInstance().

    To be honest, I can't htink of the last time I wrote a singleton...:)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Rep Power

    Default Re: Singleton eager instantiation versus lazy

    A good read about singletons, although slightly biased: Singletons Are Evil
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

Similar Threads

  1. Replies: 1
    Last Post: 09-07-2011, 07:08 AM
  2. Replies: 2
    Last Post: 10-06-2008, 10:06 PM
  3. Replies: 0
    Last Post: 03-29-2008, 01:41 PM
  4. Replies: 0
    Last Post: 09-26-2007, 09:32 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts