Double Check locking Part 2 / Using AtomicReference

When I posted the original results of some of the solutions for multi-threaded lazy initialization, there was an additional suggestion about using the AtomicReference class. The code would be something like:
private static AtomicReference
   instance = new AtomicReference();
    
    public static AtomicReferenceSingleton getDefault() {
	AtomicReferenceSingleton ars = instance.get();
	if (ars == null) {
	    instance.compareAndSet(null,
                   new AtomicReferenceSingleton());
	    ars = instance.get();
	}
	return ars;
    }
This approach about the same as the volatile solution (the results can be found http://blogs.sun.com/roller/page/cwebster?entry=double_check_locking. The summary is about a 3% penalty over a straight method call but about 6% better performance than fully synchronizing the methods.
Comments:

Why not use AtomicReferenceFieldUpdater and remove one level of indirection for the common case?: private static volatile AtomicReferenceSingleton instance; private static final AtomicReferenceFieldUpdater<MyClass,AtomicReferenceSingleton> instanceUpdater = AtomicReferenceFieldUpdater.newInstance(MyClass.class,AtomicReferenceSingleton.class,"instance"); public static AtomicReferenceSingleton getDefault() { AtomicReferenceSingleton ars = instance; if (ars == null) { AtomicReferenceSingleton() newInstance = new AtomicReferenceSingleton(); return instance.compareAndSet(null, null, newInstance) ? newInstance : instance; } return ars; } (I hope that's alright - web forms really are hopeless.)

Posted by Tom Hawtin on May 28, 2006 at 01:33 AM PDT #

Wont you not potentially have duplicate objects getting created in this example Chris ? This might be a no-no for strict singletons implementations ...

Posted by Mridul on May 30, 2006 at 01:54 PM PDT #

Post a Comment:
Comments are closed for this entry.
About

cwebster

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today