3333
3434import java .util .Collections ;
3535import java .util .HashMap ;
36- import java .util .List ;
3736import java .util .Map ;
3837
3938import org .scijava .log .LogService ;
39+ import org .scijava .plugin .AbstractSingletonService ;
4040import org .scijava .plugin .Parameter ;
4141import org .scijava .plugin .Plugin ;
42- import org .scijava .plugin .PluginInfo ;
4342import org .scijava .plugin .PluginService ;
44- import org .scijava .service .AbstractService ;
4543import org .scijava .service .Service ;
4644
4745/**
5048 * @author Curtis Rueden
5149 */
5250@ Plugin (type = Service .class )
53- public class DefaultAppService extends AbstractService implements AppService {
51+ public class DefaultAppService extends AbstractSingletonService < App > implements AppService {
5452
5553 @ Parameter
5654 private LogService log ;
@@ -65,41 +63,42 @@ public class DefaultAppService extends AbstractService implements AppService {
6563
6664 @ Override
6765 public App getApp (final String name ) {
68- return apps .get (name );
66+ return apps () .get (name );
6967 }
7068
7169 @ Override
7270 public Map <String , App > getApps () {
73- return apps ;
71+ return apps () ;
7472 }
7573
76- // -- Service methods --
74+ // -- SingletonService methods --
7775
7876 @ Override
79- public void initialize () {
80- apps = Collections .unmodifiableMap (discoverApps ());
81- log .info ("Found " + apps .size () + " applications." );
82- super .initialize ();
77+ public Class <App > getPluginType () {
78+ return App .class ;
8379 }
8480
85- // -- Helper methods --
81+ // -- Helper methods - lazy initialization --
82+
83+ /** Gets {@link #apps}, initializing if necessary. */
84+ private Map <String , App > apps () {
85+ if (apps == null ) initApps ();
86+ return apps ;
87+ }
8688
87- /** Discovers applications. */
88- private HashMap <String , App > discoverApps () {
89+ /** Initializes {@link #apps}. */
90+ private synchronized void initApps () {
91+ if (apps != null ) return ; // already initialized
8992 final HashMap <String , App > map = new HashMap <String , App >();
9093
91- final List <PluginInfo <App >> infos =
92- pluginService .getPluginsOfType (App .class );
93- for (final PluginInfo <App > info : infos ) {
94- final App app = pluginService .createInstance (info );
95- if (app == null ) continue ;
96- final String name = info .getName ();
94+ for (final App app : getInstances ()) {
95+ final String name = app .getInfo ().getName ();
9796 if (!map .containsKey (name )) {
9897 // no (higher-priority) app with the same name exists
9998 map .put (name , app );
10099 }
101100 }
102- return map ;
101+ apps = Collections . unmodifiableMap ( map ) ;
103102 }
104103
105104}
0 commit comments