Faster loading plugins with deferred service instantiation

One of the things developers do in the bundle start() method is register services (OSGI services that is). One best practice to follow is to not instantiate the underlying object until the service is requested.

In your start bundle you may have something like this in the first listing below. The problem with service registration is the object you pass in has to be instantiated.

public void start(BundleContext context) throws Exception {

mySvc = context.registerService(
MyOwnOSGIService.class.getName(),
new MyOwnOSGIService(), null);
}

The key is to use ServiceFactory as the service object so it is queried by the OSGI platform when someone asks for your service. This way, if your service does some large amount of initialization or io it will be deferred until needed.


public class MyOwnOSGIService implements ServiceFactory {

private static MyOwnOSGIService SERVICE;

public Object getService(Bundle b, ServiceRegistration reg) {
if (SERVICE == null)
SERVICE = new MyOwnOSGIService();

return SERVICE;
}
}

Tags: : :