Tulika Shil wrote:Why is it suggested that the getInstance() method in a Singleton class sould be synchonized even if the Singleton class object is declared static
Thomas Punihaole wrote:This pattern by William Pugh is thread-safe and lazy.
Hence it is the best way and considered standard practice.
Jeff Verdegan wrote:No, it's definitely not the best, and while it's fairly common, I certainly wouldn't call it "standard practice."
Cheers, Roberto Perillo
SCJP, SCWCD, SCJD, SCBCD
Roberto Perillo wrote:Agreed. I avoid using Singletons, but if I had to, I'd go for the first approach provided by Jeff in his first post.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Jeff Verdegan wrote:However, syncing is only necessary when doing lazy loading, and lazy loading is never the right approach, ...
Jesper de Jong wrote:
Jeff Verdegan wrote:However, syncing is only necessary when doing lazy loading, and lazy loading is never the right approach, ...
Can you explain why lazy loading is never the right approach?
Jeff Verdegan wrote:However, as I understand it, neither the JLS nor the JVM spec actually requires that classes be loaded on demand; it just so happens that that's what every major JSE VM does.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Winston Gutkowski wrote:
I agree with everything else you say, but I have a question: Does simply declaring a variable, eg:
private Singleton s;
count as a 'reference'? Because if so, you could have the case of a class that needs to declare it without actually using it.
Winston
http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html wrote:A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the reference to the field is not a compile-time constant (ยง15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization.
Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Cheers, Roberto Perillo
SCJP, SCWCD, SCJD, SCBCD
Bras cause cancer. And tiny ads:
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
|