Monday, 17th October 2011
Follow WikiJava on twitter now. @Wikijava

Talk:Singleton Factory patterns example

From WikiJava

Jump to: navigation, search

Alcor - 5 Point(s)

Very nice! Patterns are really powerful. I have to learn them as soon as possibile.

Thank you.


Singleton Pattern You created the Singleton article. I have two notes:

1.) In the LazySingletonFactory example, is there a possibility that in multithreaded environment, more than one Singleton objects are created? That can happen when two thread calls the getSingletonFactory() method in the same time, and the first time. Most of the time this is not a problem, but in some cases when you must have only one instance of the singleton that should be in mind.

2.) The Lazy aspect of the examples only refers to the factory object, and not for singleton objects. Those are created right away when the factory is created

So, I would create the factory object always "normaly". And the singeleton objects could be either created normaly or lazyly. Ervinn 15:17, 2 June 2008 (PDT)

Hi Ervinn,
1)Indeed looking at the example I realized that your point is good: there is the possibility that in a multithreaded execution one thread stops the execution in the public static LazySingletonFactory getSingletonFactory() just after the if clause and before the singletonFactory = new LazySingletonFactory(); command. Eventually another thread could call the same method in that moment and obtain an object, that would NOT be the same object returned in the first thread. To solve this we need to make the method getSingletonFactory() synchronized, this will prevent this situation to happen.
Yes, making getSingletonFactory() synchronized would solve the problem. But synchronization is expensive for performance point of you. So instead, synchronization clause should be used, but only when the singleton object is not created yet. For example:
    public static LazySingletonFactory getSingletonFactory() {
	if (singletonFactory == null) {
                   synchronized {
                     if ( singletonFactory == null ) {
	       singletonFactory = new LazySingletonFactory();
                      }
                   }
	}
	return singletonFactory;
    }
Ervinn 18:08, 3 June 2008 (PDT)
2)Indeed the examples proposed are half lazy, the object contained is instanced only when the singleton is. Indeed it may be a good idea to make the singleton object not lazy and then decide case per case the best moment for creating the contained object. The lazy approach may not always be the best.
thanks for sharing your opinion, --DonGiulio 16:50, 2 June 2008 (PDT)