aboutsummaryrefslogtreecommitdiff
path: root/usage_examples/GetterLazyExample_post.jpage
blob: 5f34c43e62639d4ea3ceaa48aabeb41b0c02bbac (plain)
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
public class GetterLazyExample {
	private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();
	
	public double[] getCached() {
		java.lang.Object value = this.cached.get();
		if (value == null) {
			synchronized(this.cached) {
				value = this.cached.get();
				if (value == null) {
					final double[] actualValue = expensive();
					value = actualValue == null ? this.cached : actualValue;
					this.cached.set(value);
				}
			}
		}
		return (double[])(value == this.cached ? null : value);
	}
	
	private double[] expensive() {
		double[] result = new double[1000000];
		for (int i = 0; i < result.length; i++) {
			result[i] = Math.asin(i);
		}
		return result;
	}
}