| Class | Line # | Actions | |||||
|---|---|---|---|---|---|---|---|
| StatefulSupplier | 13 | 1 | 0% | 1 | 2 | ||
| ThreadSafeSupplierImpl | 28 | 6 | 0% | 2 | 8 |
| 1 | package guru.mikelue.foxglove.functional; | |
| 2 | ||
| 3 | import java.util.concurrent.locks.Lock; | |
| 4 | import java.util.concurrent.locks.ReentrantLock; | |
| 5 | import java.util.function.Supplier; | |
| 6 | ||
| 7 | /** | |
| 8 | * In order to prevent state pollution when cloning {@link Supplier}s, | |
| 9 | * this interface marks the {@link Supplier} as stateful. | |
| 10 | * | |
| 11 | * @param <T> The type of results supplied by this supplier | |
| 12 | */ | |
| 13 | public interface StatefulSupplier<T> extends Supplier<T> { | |
| 14 | /** | |
| 15 | * Turns a thread-safe version of the given stateful supplier. | |
| 16 | * | |
| 17 | * @param <T> The type of results supplied by this supplier | |
| 18 | * @param sourceSupplier The source stateful supplier | |
| 19 | * | |
| 20 | * @return The thread-safe stateful supplier | |
| 21 | */ | |
| 22 | 0 | static <T> StatefulSupplier<T> threadSafe(StatefulSupplier<T> sourceSupplier) |
| 23 | { | |
| 24 | 0 | return new ThreadSafeSupplierImpl<>(sourceSupplier); |
| 25 | } | |
| 26 | } | |
| 27 | ||
| 28 | class ThreadSafeSupplierImpl<T> implements StatefulSupplier<T> { | |
| 29 | private final Lock lock = new ReentrantLock(); | |
| 30 | private final StatefulSupplier<? extends T> sourceSupplier; | |
| 31 | ||
| 32 | 0 | ThreadSafeSupplierImpl(StatefulSupplier<? extends T> sourceSupplier) |
| 33 | { | |
| 34 | 0 | this.sourceSupplier = sourceSupplier; |
| 35 | } | |
| 36 | ||
| 37 | 0 | @Override |
| 38 | public T get() | |
| 39 | { | |
| 40 | 0 | lock.lock(); |
| 41 | ||
| 42 | 0 | try { |
| 43 | 0 | T value = (T)sourceSupplier.get(); |
| 44 | 0 | return value; |
| 45 | } finally { | |
| 46 | 0 | lock.unlock(); |
| 47 | } | |
| 48 | } | |
| 49 | } |