Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c0de1429f3f30abe8ecaa954fd52418bb9efc06c (plain) (blame)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*******************************************************************************
 * Copyright (c) 2014, 2016 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.osgi.internal.container;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;

/**
 * A helper class for doing lazy initialization 
 * 
 * @param <V> the type of object to lazy initialize
 */
public class AtomicLazyInitializer<V> {
	private final AtomicReference<V> holder = new AtomicReference<>();

	/**
	 * Gets the current value.  If the value has not been initialized then
	 * {@code null} is returned;
	 * @return the current value
	 */
	public final V get() {
		return holder.get();
	}

	/**
	 * Atomically gets the current initialized value.  If the current value is {@code null}
	 * then the supplied initializer is called to create the value returned.
	 * @param initializer the initializer to call if the current value is {@code null}
	 * @return the initialized value.  May return {@code null} if initializer returns null.
	 */
	public final V getInitialized(Callable<V> initializer) {
		V result = holder.get();
		if (result != null) {
			return result;
		}
		// Must hold a lock to ensure the operation is atomic.
		synchronized (holder) {
			result = holder.get();
			if (result != null) {
				return result;
			}
			try {
				result = initializer.call();
			} catch (Exception e) {
				unchecked(e);
			}
			holder.set(result);
			return result;
		}
	}

	/**
	 * Gets the current value and clears the value for future calls to this lazy initializer.
	 * @return the current value
	 */
	public final V getAndClear() {
		return holder.getAndSet(null);
	}

	private static <T> T unchecked(Exception exception) {
		return AtomicLazyInitializer.<T, RuntimeException> unchecked0(exception);
	}

	@SuppressWarnings("unchecked")
	private static <T, E extends Exception> T unchecked0(Exception exception) throws E {
		throw (E) exception;
	}
}

Back to the top