SCJP, SCWCD, SCBCD, SCEA 5
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Originally posted by Edwin Dalorzo:
However you must syncrhonize at least your getInstance() method to avoid two threads create an instance of your Singleton class simultaneously.
Originally posted by Edwin Dalorzo:
The static variable initializer approach implies that you initialize the Singlenton instance when the class is first loaded by the ClassLoader.
Originally posted by Edwin Dalorzo:
What if you need to pass some parameters to the class to initialize it? You cannot do that in the static initializer if you know the value of the parameters until the moment your first create the Singleton instance.
Originally posted by Edwin Dalorzo:
Another disadventage of static intializer has to do with the exception handling. Since the static intializer is executed by the JVM when the class is first loaded, there is no way to throw an exception from the initialization block, which you could better control with a getInstance method.
Originally posted by Edwin Dalorzo:
On the other hand, the double check locking idiom is not implicit in the syncrhonization of the getIntance method, not even if you use a synchronized block. It happens when you read the value of the instance variable out of the syncrhonied block to control the execution of the synchronized block. If anoter thead had read the variable a nanosecond before, than two threads may enter the synchronized block and intialized the object twice.
Ken, why do you suggest this is implicit in a synchronized getInstance method?
Originally posted by Mohamed Farouk:
Dear Friends
I have a question If I create a singleton class with no state (I mean no instance attributes). But I have many instance methods in it with local variables and static attributes only. Can this object handle concurrent request from multiple threads at the same time. Will there be any impact on object interms of contention(threads waitin for this object). If I understand right unless a method or code block is synchronized in the code ed the jvm does not create locks or monitors.
Please help me as I am thinking of creating a DAO as singleton and just thinking of Contention/performance.
Regards
Farouk
SCJP, SCWCD, SCBCD, SCEA 5
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Don't get me started about those stupid light bulbs. |