aspose file tools*
The moose likes Threads and Synchronization and the fly likes Double check locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Double check locking" Watch "Double check locking" New topic
Author

Double check locking

Avinash Tiwari
Ranch Hand

Joined: Sep 20, 2006
Posts: 50
Hi All,
Generally we see Double check locking in code across many places. I have read many articles and need respected people opinion.

Is there any alternative to double check locking.

Or using volatile and another instance reference in the method we can solve it.

Please let me know.

Thanks
Avinash


Work hard and rest not till the job is done....
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

In what particular context are you talking about using double check locking?

The general consensus is that you shouldn't use it if you can avoid it - because in several versions of Java it is impossible to actually achieve properly and in the versions that it isn't broken in, it is still overly complicated. There are often better solutions, but the solution depends on the context in which you are using it.


Steve
Avinash Tiwari
Ranch Hand

Joined: Sep 20, 2006
Posts: 50
Hi
Thanks for the reply.
I am talking in terms of singleton usage.
Can you please let me know better options.
Thanks
Avinash
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1017
    
  15
I found the following way quite ok. It's not my own code. I had referred to this page - http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/



Not sure if this is a safe way, cause like Steve said, it would depend on what you require the Singleton for and on your particular use case.

I remember reading somewhere that we can use a factory to ensure that the class has this one object( or the number of objects we require) only. The job of the singleton class is generally not to ensure that there is one object but to have the object do whatever methods provide for. Not sure how we'd do it with an abstract factory. I'm trying it right now. Will post/seek help, depending on my progress. We'd probably go for this option only if we can't use enums for some reason.

Let us see what the experts have to say ( I hope you all would still respond on this one - I didn't really mean to hijack this topic; just that I'm also revising and (re)working on singleton pattern currently.)

Thanks for your help.
Chan.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

The absolute best way to do a singleton is this:

It is guaranteed to give you a single instance in any situation where having a single instance is feasible, and is downright simple. The only time you should not use this approach is if you need lazy initialization, in which case Chan's code is way to go. There is a variation on the code that Chan provided that is a bit simpler and relies on enums:
You use it like MySingleton.INSTANCE.whatever(). The principle is the same as Chan's using a static inner class to delay creating the instance (because that is essentially how enums work) and relying on the synchronization of the class loading mechanism to ensure it happens just once.
Avinash Tiwari
Ranch Hand

Joined: Sep 20, 2006
Posts: 50
Thanks for the kind reply.

Please help to provide further answers. Apart from singleton usage , where else we can utilize the double check locking or has a chance of being used and the alternatives that might be available.

Thanks
Avinash
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

I am not going to brainstorm for when you might use a mechanism I don't think you should use. But if you come up with some, I would be willing to discuss alternatives.

The general reason for double check locking is:
1) You need to set a value, but need to set it only once
2) You want to avoid the cost of synchronization, so you check the value to see if it needs to be set before synchronizing
3) You need to check again, because the value you need to set could have changed while you waited for the synchronization lock

Most of the time, the cost of synchronization is overstated, and double check locking is not necessary at all. Just synchronize and check within the synchronized block, and be done with it. Assuming you need to avoid the cost of synchronization is a micro- and premature optimization. You should spend your time elsewhere.

Much of the time (like the Singleton case) there is no need for the synchronization because it can be handled during class or instance initialization. People only don't do it there because of the belief that lazy initialization is better - but most of the time this is an assumption not a measured reality. It is another premature optimization that adds complexity but not value.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3014
    
  10
Avinash Tiwari wrote:Is there any alternative to double check locking.

Or using volatile and another instance reference in the method we can solve it.

There are many alternatives, as Chan Ag's link shows. But I want to add: if you do use double-checked locking, you need to use volatile as well, to mark the field you use to reference the singleton instance. If you don't use volatile, it won't work reliably in multithreaded environments. You also need to be using JDK 1.5 or later, as earlier versions did not implement volatile reliably.

But as others have said, there are plenty of alternatives which are often better. Including: don't try to make a singleton at all, if you don't have a good reason you need a singleton. Their usefulness is greatly exaggerated.
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1017
    
  15
Thanks Steve, and Mike for helping me again.

My part of the query is addressed already I have it in my plan ( by this weekend I will try to complete it ) to work on creating Object pool of some sort and dispense objects on need. If I'd have questions on it, I will post them as a separate thread. I will try my best to not have questions this time. :-)

Thank you.
Chan.

Avinash Tiwari
Ranch Hand

Joined: Sep 20, 2006
Posts: 50
Thanks you all for your replies.

On similar lines , we say Singleton is one per JVM. So in distributed environment , let's say we have 2-3 JVMs. That means we will have 2-3 Singleton instances.

The question is how do we maintain the state of singleton or determine we have one with all same states.

Please let me know.

Thanks
Avinash
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

A singleton isn't one per jvm, it is one per classloader. A simple app may have just one classloader but a web app may have many, and some desktop apps may have more than one as well.

How do you get a singleton implemented across a distributed application? You can't. The best you can do is maintain state in a central data store (like a database) and have any class who needs the state to read and write there. And for that there is no need for a singleton.
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1506
    
    5

Hi,

It looks like most of the queries are already answered

However, I would put a little case for DCL (doubly checked locking).

Apart from singleton, sometimes, DCL is actually helpful. e.g. there is an expensive operation - which does some data analysis and populates a map; and, due to some reason, it may happen that a bunch of threads attempt to populate the map. However, what we want is - if a particular version of map is populated, we don't want to do it again.

DCL to the rescue:Now, what we are doing here is - firstly, initializing the map, and then populating it.

We may run in serious trouble if:
1) Thread A initializes map, but has not yet populated it completely
2) Thread B checks that map is not null (and assumes that it has already been populated)
3) Thread B provides this (partially populated) map to its consumer - which may run into further issues

The idea is - in DCL, all we have to make sure is - for condition X (which we are checking as deciding factor), the state of X must change in atomic manner, and it must be done 'after' the innermost block is executed.
So, the better version would be:This way, Thread B will get non-null map only when it is really populated.

Why we should not use DCL for singleton construction is because - most of the time, we start populating the same INSTANCE whose null-ness we are checking as DCL condition. Since object construction is not atomic, it is generally discouraged.

However, DCL and singleton are two separate things, and improper usage of DCL can cause pretty worse issues (which, as per the Murphy's law, will manifest only in production environment )

Just my two cents.

P.S. btw, the best way to have a singleton would be - to use enum


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3014
    
  10
Ummm, to reiterate my last post, as applied to Anayonkar Shivalkar's post: the variable "map" really, really needs to be volatile there. Or your code DOES NOT WORK. Not reliably, anyway. (And also you need to be using at least JDK 1.5, but that's almost a given, these days.)
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1506
    
    5

Mike Simmons wrote:Ummm, to reiterate my last post, as applied to Anayonkar Shivalkar's post: the variable "map" really, really needs to be volatile there. Or your code DOES NOT WORK. Not reliably, anyway. (And also you need to be using at least JDK 1.5, but that's almost a given, these days.)

I just can't believe that I missed to mention this
Yes, map has to be volatile.
Thanks Mike!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double check locking