aboutsummaryrefslogtreecommitdiff
path: root/usage_examples/GetterLazyExample_post.jpage
blob: afed1748229d105f8f351aa92bbb1059006c7e4b (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(value) {
				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;
	}
}