My favorites | Sign in
Project Logo
                
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.wideplay.warp.util;

import com.google.inject.Provider;
import net.jcip.annotations.ThreadSafe;

/**
* Utility to lazily load an object reference.
* It uses Double-Checked Locking under the covers
* and thus can safely be accessed from multiple threads
* concurrently.
*
* @author Robbie Vanbrabant
*/
@ThreadSafe
public class LazyReference<T> {
private final Object LOCK = new Object();
// This field has to be volatile. Do not change!
private volatile T instance;
private final Provider<T> instanceProvider;

private LazyReference(Provider<T> instanceProvider) {
this.instanceProvider = instanceProvider;
}

/**
* Get the existing T instance, or lazily initialize T using
* {@link #instanceProvider}.
* @return the T instance unique to this LazyReference
*/
public T get() {
// Double-Checked Locking as seen in
// Effective Java, 2nd edition, page 283.
T result = instance;
if (result == null) {
synchronized (LOCK) {
result = instance;
if (result == null) {
instance = result = instanceProvider.get();
}
}
}
return result;
}

/**
* Create a lazy reference with a provider of the
* eventual instance.
* @param instanceProvider a {@link com.google.inject.Provider}
* that gives out the eventual instance,
* usually an expensive operation
* @return an uninitialized reference to T
*/
public static <T> LazyReference<T> of(Provider<T> instanceProvider) {
return new LazyReference<T>(instanceProvider);
}
}
Show details Hide details

Change log

r128 by robbie.vanbrabant on Aug 23, 2008   Diff
Javadoc
Go to: 
Project members, sign in to write a code review

Older revisions

r127 by robbie.vanbrabant on Aug 23, 2008   Diff
Double-Checked Locking utility. We'll
need that for all persistence
strategies, and we shouldn't be
repeating ourselves.
All revisions of this file

File info

Size: 1733 bytes, 56 lines
Hosted by Google Code