Importing an Optional Service

Sometimes a bundle considers one or more of its imported services as optional. Most of the time a bundle absolutely requires all of its imported services, but there are occasions where this can be useful.

Requesting an optional imported service is very similar to requesting a required imported services. The method getOptionalImportedServiceNames() is used to specify the optional services. For example given the following required imported services:

  protected String[] getImportedServiceNames() {
    return new String[] {
      VendorService.SERVICE_NAME,
      NapkinService.SERVICE_NAME
    };
  }

The NapkinService can be made optional by moving to the following method:

  protected String[] getOptionalImportedServiceNames() {
    return new String[] {
      NapkinService.SERVICE_NAME
    };
  }

Now that the NapkinService has been made optional, the bundle activator's activate() method will be called when the bundle is started regardless of the availability of the NapkinService.

The following methods should be implemented to handle the acquisition and release of optional imported services:

These methods are used to bind and unbind the optional imported services, for example:

protected void handleAcquiredOptionalImportedService(String serviceName, Object service) {
  if (serviceName.equals(NapkinService.SERVICE_NAME)) {
    NapkinService napkin = (NapkinService) service;
    Customer customer = getCustomer();
    customer.setNapkin(napkin);
  } else {
    super.handleAcquiredOptionalImportedService(serviceName, service);
  }
}

protected void handleReleasedOptionalImportedService(String serviceName, Object service) {
  if (serviceName.equals(NapkinService.SERVICE_NAME)) {
    Customer customer = getCustomer();
    customer.setNapkin(null);
  } else {
    super.handleReleasedOptionalImportedService(serviceName, service);
  }
}
Circular Dependencies

Circular References

One of the assumptions SAT makes is that a bundle only exports its services and is activated after its imported services have been acquired. This assumption might be too constraining for some bundles, and can cause a problem when there is a chain of circular references of imported and exported services.

A chain of circular references will prevent all the bundles in the chain from being activated since they will be deadlocked waiting to acquire their imported services.