180 |
ilm |
1 |
/*
|
|
|
2 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
|
|
|
3 |
*
|
|
|
4 |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
|
|
|
5 |
*
|
|
|
6 |
* The contents of this file are subject to the terms of the GNU General Public License Version 3
|
|
|
7 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
|
|
|
8 |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
|
|
|
9 |
* language governing permissions and limitations under the License.
|
|
|
10 |
*
|
|
|
11 |
* When distributing the software, include this License Header Notice in each file.
|
|
|
12 |
*/
|
|
|
13 |
|
|
|
14 |
package org.openconcerto.utils.function;
|
|
|
15 |
|
|
|
16 |
import java.util.Objects;
|
|
|
17 |
import java.util.function.Supplier;
|
|
|
18 |
|
|
|
19 |
import net.jcip.annotations.GuardedBy;
|
|
|
20 |
import net.jcip.annotations.ThreadSafe;
|
|
|
21 |
|
|
|
22 |
/**
|
|
|
23 |
* A Supplier that always returns the same value. Functional in the sense, that for the same input
|
|
|
24 |
* (indeed none in this case) it returns the same output.
|
|
|
25 |
*
|
|
|
26 |
* @author sylvain
|
|
|
27 |
* @param <T> the type of results supplied by this supplier.
|
|
|
28 |
*/
|
|
|
29 |
@ThreadSafe
|
|
|
30 |
public abstract class FunctionalSupplier<T> implements Supplier<T> {
|
|
|
31 |
// Not an interface to restrict implementations (even inadvertently with the :: notation)
|
|
|
32 |
|
|
|
33 |
@ThreadSafe
|
|
|
34 |
static final class LazyValue<T> extends FunctionalSupplier<T> {
|
|
|
35 |
|
|
|
36 |
private final Supplier<T> supplier;
|
|
|
37 |
@GuardedBy("this")
|
|
|
38 |
private boolean set;
|
|
|
39 |
@GuardedBy("this")
|
|
|
40 |
private T value;
|
|
|
41 |
|
|
|
42 |
LazyValue(final Supplier<T> supplier) {
|
|
|
43 |
super();
|
|
|
44 |
this.supplier = Objects.requireNonNull(supplier);
|
|
|
45 |
this.set = false;
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
@Override
|
|
|
49 |
public synchronized T get() {
|
|
|
50 |
if (!this.set) {
|
|
|
51 |
this.value = this.supplier.get();
|
|
|
52 |
this.set = true;
|
|
|
53 |
}
|
|
|
54 |
return this.value;
|
|
|
55 |
}
|
|
|
56 |
|
|
|
57 |
@Override
|
|
|
58 |
public String toString() {
|
|
|
59 |
return this.getClass().getSimpleName() + " for " + this.supplier;
|
|
|
60 |
}
|
|
|
61 |
}
|
|
|
62 |
|
|
|
63 |
static public final <U> FunctionalSupplier<U> get(Supplier<U> orig) {
|
|
|
64 |
return orig instanceof FunctionalSupplier ? (FunctionalSupplier<U>) orig : new LazyValue<>(orig);
|
|
|
65 |
}
|
|
|
66 |
|
|
|
67 |
static public final <U> ConstantSupplier<U> getConstant(U value) {
|
|
|
68 |
return new ConstantSupplier<>(value);
|
|
|
69 |
}
|
|
|
70 |
|
|
|
71 |
// not public to restrict implementations
|
|
|
72 |
FunctionalSupplier() {
|
|
|
73 |
}
|
|
|
74 |
}
|