|
| 1 | +/** |
| 2 | + * |
| 3 | + */ |
| 4 | +package net.imglib2.algorithm.util; |
| 5 | + |
| 6 | +import java.util.HashMap; |
| 7 | + |
| 8 | +/** |
| 9 | + * Manage named singleton instances. |
| 10 | + * |
| 11 | + * Useful for sharing instances of objects between threads. |
| 12 | + * |
| 13 | + * Our most relevant use case for this is to share cached ImgLib2 cell images |
| 14 | + * such as N5 datasets and lazily generated cell images between tasks of a Spark |
| 15 | + * cluster running on the same executor. |
| 16 | + * |
| 17 | + * Example: |
| 18 | + * |
| 19 | + * <pre> |
| 20 | + * final String url = "https://janelia-cosem.s3.amazonaws.com/jrc_hela-2/jrc_hela-2.n5"; |
| 21 | + * final String dataset = "/em/fibsem-uint16/s4"; |
| 22 | + * |
| 23 | + * final N5Reader n5 = Singleton.get( |
| 24 | + * url, |
| 25 | + * () -> new N5Factory().openReader( url ) ); |
| 26 | + * |
| 27 | + * final RandomAccessibleInterval< T > img = Singleton.get( |
| 28 | + * url + ":" + dataset, |
| 29 | + * () -> N5Utils.open( n5, dataset ) ); |
| 30 | + * </pre> |
| 31 | + * |
| 32 | + * @author Stephan Saalfeld |
| 33 | + * |
| 34 | + */ |
| 35 | +public class Singleton |
| 36 | +{ |
| 37 | + @FunctionalInterface |
| 38 | + public static interface ThrowingSupplier< T, E extends Exception > |
| 39 | + { |
| 40 | + public T get() throws E; |
| 41 | + } |
| 42 | + |
| 43 | + private Singleton() |
| 44 | + {} |
| 45 | + |
| 46 | + static private HashMap< String, Object > singletons = new HashMap<>(); |
| 47 | + |
| 48 | + /** |
| 49 | + * Remove and retrieve a named singleton instance. |
| 50 | + * |
| 51 | + * @param key |
| 52 | + * @return |
| 53 | + */ |
| 54 | + public static synchronized Object remove( final String key ) |
| 55 | + { |
| 56 | + return singletons.remove( key ); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Get or create the named singleton instance of T. |
| 61 | + * |
| 62 | + * @param <T> |
| 63 | + * @param <E> |
| 64 | + * @param key |
| 65 | + * @param supplier |
| 66 | + * @return |
| 67 | + * @throws E |
| 68 | + */ |
| 69 | + public static synchronized < T, E extends Exception > T get( final String key, final ThrowingSupplier< T, E > supplier ) throws E |
| 70 | + { |
| 71 | + @SuppressWarnings( "unchecked" ) |
| 72 | + final T t = ( T ) singletons.get( key ); |
| 73 | + if ( t == null ) |
| 74 | + { |
| 75 | + final T s = supplier.get(); |
| 76 | + singletons.put( key, s ); |
| 77 | + return s; |
| 78 | + } |
| 79 | + else |
| 80 | + return t; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Clear all named singletons. |
| 85 | + */ |
| 86 | + public static synchronized void clear() |
| 87 | + { |
| 88 | + singletons.clear(); |
| 89 | + } |
| 90 | +} |
0 commit comments