You are on page 1of 6

7/14/13

Synchronization for Singleton (Java in General forum at JavaRanch)

A friendly place for programming greenhorns!

Big Moose Saloon


Search

Java FAQ

Recent Topics

Register / Login

JavaRanch Java Forums Java Java in General

Author

Synchronization for Singleton


posted 1/10/2012 12:04:07 AM

Tulika Shil Greenhorn Joined: Jan 09, 2012 Posts: 3

Why is it suggested that the getInstance() method in a Singleton class sould be synchonized even if the Singleton class object is declared static

Roberto Perillo Bartender Joined: Dec 28, 2007 Posts: 2223


I like...

posted 1/10/2012 12:15:59 AM

Howdy, Tulika. Welcome to JavaRanch! Please take a look here. I think it might be helpful!

C heers, Bob "John Lennon" Perillo SC JP, SC WC D, SC JD, SC BC D - Daileon: A Tool for Enabling Domain Annotations

Jeff Verdegan Bartender Joined: Jan 03, 2004 Posts: 6109

posted 1/10/2012 2:15:30 AM

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

6 "Even if the variable is declared static" has nothing to do with it. (And note, it's the variable that's static, not the object. Objects do not have the property of being static or non-static.) Whether a variable is static or not, if multiple threads can access it concurrently and one or more of those threads could be writing it, then all access to it has to be synchronized (or, in some cases, just declaring it volatile is enough, but not in this case). However, syncing is only necessary when doing lazy loading, and lazy loading is never the right approach, so if you do your singleton right, you don't need to sync the getInstance() method.

I like...

www.coderanch.com/t/563967/java/java/Synchronization-Singleton

1/6

7/14/13
view plain

Synchronization for Singleton (Java in General forum at JavaRanch)


c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 . 0 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 . 2 1 . 2 2 . 2 3 . 2 4 . 2 5 .

/ /c o r r e c t p u b l i cc l a s sS i n g l e{ p r i v a t es t a t i cf i n a lS i n g l ei n s t a n c e=n e wS i n g l e ( ) ; p u b l i cs t a t i cS i n g l eg e t I n s t a n c e ( ){ r e t u r ni n s t a n c e ; } / /. . .r e s to fc l a s s. . . } / /i n f e r i o ra p p r o a c h ,p o i n t l e s sl a z yl o a d i n g ,s y n c i n gi sn e c e s s a r y p u b l i cc l a s sS i n g l e{ p r i v a t es t a t i cS i n g l ei n s t a n c e ; p u b l i cs t a t i cs y n c h r o n i z e dS i n g l eg e t I n s t a n c e ( ){ i f( i n s t a n c e= =n u l l ){ i n s t a n c e=n e wS i n g l e ( ) ; } r e t u r ni n s t a n c e ; } / /. . .r e s to fc l a s s. . . }

In the second example, we need syncing because otherwise multiple threads could all see true for "instance == null" and then each would create its own instance.

Thomas Punihaole Greenhorn Joined: Jan 12, 2012 Posts: 4

posted 1/13/2012 9:16:39 AM

This pattern by William Pugh is thread-safe and lazy. Hence it is the best way and considered standard practice. http://en.wikipedia.org/wiki/Singleton_pattern

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 . 0 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 .

p u b l i cc l a s sS i n g l e t o n{ / /P r i v a t ec o n s t r u c t o rp r e v e n t si n s t a n t i a t i o nf r o mo t h e rc l a s s e s p r i v a t eS i n g l e t o n ( ) { } / * * *S i n g l e t o n H o l d e ri sl o a d e do nt h ef i r s te x e c u t i o no fS i n g l e t o n . g e t I n s t a n c e ( ) *o rt h ef i r s ta c c e s st oS i n g l e t o n H o l d e r . I N S T A N C E ,n o tb e f o r e . * / p r i v a t es t a t i cc l a s sS i n g l e t o n H o l d e r{ p u b l i cs t a t i cf i n a lS i n g l e t o ni n s t a n c e=n e wS i n g l e t o n ( ) ; } p u b l i cs t a t i cS i n g l e t o ng e t I n s t a n c e ( ){ r e t u r nS i n g l e t o n H o l d e r . i n s t a n c e ; } }

Jeff Verdegan Bartender Joined: Jan 03,

posted 1/13/2012 5:55:07 PM

www.coderanch.com/t/563967/java/java/Synchronization-Singleton

2/6

7/14/13
Joined: Jan 03, 2004 Posts: 6109

Synchronization for Singleton (Java in General forum at JavaRanch)


Thomas Punihaole wrote:

This pattern by William Pugh is thread-safe and lazy.

6
I like...

It also adds an extra level of complexity, and lazy loading is never necessary or even beneficial.

Hence it is the best way and considered standard practice.

No, it's definitely not the best, and while it's fairly common, I certainly wouldn't call it "standard practice."

Roberto Perillo Bartender Joined: Dec 28, 2007 Posts: 2223


I like...

posted 1/13/2012 6:13:21 PM


Jeff Verdegan wrote:

No, it's definitely not the best, and while it's fairly common, I certainly wouldn't call it "standard practice."

Agreed. I avoid using Singletons, but if I had to, I'd go for the first approach provided by Jeff in his first post.
Winston Gutkowski Bartender Joined: Mar 17, 2011 Posts: 4972

posted 1/13/2012 7:16:46 PM


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.

Personally, I quite like: 7


I like... view plain c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 .

p u b l i ce n u mS i n g l e t o n{ I N S T A N C E ; . . . }

but yes, for a class, I've only ever found one case for using Pugh's "initialize-on-demand class holder idiom". It's too much of a mouthful anyway. Winston

Isn't it funny how there's always time and money enough to do it WRONG?

Jesper de Jong Java C owboy Bartender Joined: Aug 16, 2005 Posts: 13022

posted 1/13/2012 7:43:44 PM


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? 5
I like...

Java Beginners FAQ - JavaRanch SC JP FAQ - The Java Tutorial - Java SE 7 API documentation Scala Notes - My blog about Scala

posted 1/13/2012 8:04:18 PM www.coderanch.com/t/563967/java/java/Synchronization-Singleton

Jeff Verdegan

3/6

7/14/13

Jeff Verdegan Bartender Joined: Jan 03, 2004 Posts: 6109

Synchronization for Singleton (Java in General forum at JavaRanch)


posted 1/13/2012 8:04:18 PM
Jesper de Jong wrote: Jeff Verdegan wrote:

However, syncing is only necessary when doing lazy loading, and lazy loading is never the right

6
I like...

approach, ...

C an you explain why lazy loading is never the right approach?

Let me state up front that by "lazy loading" I assume we're talking about "lazy instantiation" of the Singleton instance. If somebody's talking about something else, please let me know. My thinking goes like this: What's the point of lazy instantiation? To avoid incurring the cost of constructing the singleton unnecessarily. However, the usual use of a Singleton is

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 .

S i n g l e t o ns=S i n g l e t o n . g e t I n s t a n c e ( ) ; s . d o S t u f f ( ) ;

Lazy instantiation buys us nothing here. If we're going to use it, we have to construct it. Since Java loads classes on demand, our Singleton class won't be loaded until we use it, so we won't incur the cost of eagerly instantiating the object until we're on the verge of using it. So when might lazy instantiation be useful? The only case would be if we're using the class but not using the instance, or not using it until some time later:
view plain c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 .

S i n g l e t o n . s o m e S t a t i c M e t h o d ( ) ; S i n g l e t o n . s o m e O t h e r S t a t i c M e t h o d ( ) ; . . . / /m u c hl a t e r ,o rp o s s i b l yn o ta ta l l S i n g l e t o ns=S i n g l e t o n . g e t I n s t a n c e ( ) ; s . d o S t u f f ( ) ;

So we might decide that we don't want to incur the cost of construction of the instance upon loading the class when we're just using the static methods. Defer that cost until we need it, and don't incur it at all, if not needed. So here we would use lazy instantiation, so that we can use the class without incurring the overhead of constructing the instance. But if this is your use case, you almost certainly have a design flaw. What would be the case where you would actively use a bunch of static methods in your singleton, but never instantiate it, or instantiate it somewhere distant from the use of the static methods? That sounds like a serious failure of separation of responsibility. Add to that the fact that in almost every case, instantiation is not a heavyweight or expensive operation, and there's just no real practical benefit.
www.coderanch.com/t/563967/java/java/Synchronization-Singleton 4/6

7/14/13

Synchronization for Singleton (Java in General forum at JavaRanch)

Now, I can see one specific use case where it could be valuable. All of the above is predicated on the idea that a class is not loaded until it's referenced. That is, the early part of your program won't suffer from incurring the cost of instantiating a singleton that's not used until later. 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. However, if some particular JVM that you're targeting is observed to load all its classes on startup, AND if your singleton is expensive to construct, AND if it's not used until later in the program or potentially not at all, THEN, and only then, as far as I can tell, might lazy instantiation be useful.
Winston Gutkowski Bartender Joined: Mar 17, 2011 Posts: 4972

posted 1/13/2012 8:26:22 PM

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.

7
I like...

Actually, according to Josh Bloch, JLS 12.4.1 does make that guarantee; but it's quite a big para and I haven't bothered to check. I agree with everything else you say, but I have a question: Does simply declaring a variable, eg: p r i v a t eS i n g l e t o ns ; 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

Jeff Verdegan Bartender Joined: Jan 03, 2004 Posts: 6109

posted 1/13/2012 8:40:38 PM


Winston Gutkowski wrote:

I agree with everything else you say, but I have a question: Does simply declaring a variable, eg: p r i v a t eS i n g l e t o ns ;

6
I like...

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

I don't think simply having that declaration causes the class to be loaded, nor, for that matter, does having, say, a call to s.foo() inside an if block that never gets executed. But a) it's easy enough to test, and b) I still don't see a real-world situation arising where that happens AND the singleton is expensive to construct AND the use of the instance is so distant or never occurs at all such that instantiating it early actually causes a problem.

Rob Spoor Sheriff Joined: Oct 27, 2005 Posts: 19242


I like...

posted 1/13/2012 8:45:47 PM

The relevant part:


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 C lass and in package java.lang.reflect also causes class or

www.coderanch.com/t/563967/java/java/Synchronization-Singleton

5/6

7/14/13

Synchronization for Singleton (Java in General forum at JavaRanch)


interface initialization. A class or interface will not be initialized under any other circumstance.

SC JP 1.4 - SC JP 6 - SC WC D 5 How To Ask Questions How To Answer Questions

Roberto Perillo Bartender Joined: Dec 28, 2007 Posts: 2223


I like...

posted 1/13/2012 9:13:40 PM

In 2010, some guys of the magazine where I publish articles and work as tech member interviewed the GoF. When they were asked what were the patterns that they would take off the book if it was today, the first pattern that they mentioned: Singleton.

Jeff Verdegan Bartender Joined: Jan 03, 2004 Posts: 6109

posted 1/13/2012 9:24:07 PM


Rob Spoor wrote:

The relevant part:

6
I like...

Thanks Rob. I was too lazy too look, and didn't expect it to be spelled out that directly.

I agree. Here's the link: http://aspose.com/file-tools

subject: Synchronization for Singleton

Similar Threads singleton class Singleton class Speaks anything against this Singleton implementation? singleton class what is a singleton class?
All times above are in your local time zone & format.T he current ranch time (not your local time) is Jul 14, 2013 08:42:09 .

Contact Us | Powered by JForum |

C opyright 1998-2013 Paul W he aton

www.coderanch.com/t/563967/java/java/Synchronization-Singleton

6/6

You might also like