Search code examples
javaosgiequinoxbundles

Service References in OSGi


Once an instance of an OSGi service is retrieved from the bundle context does it become invalidated when the service is stopped?

My initial tests show that the service instance can be used even after the service bundle is stopped, which contradicts my understanding of the dynamic nature of OSGi.

I suppose this boils down to what retrieving a service (via ServiceTracker) from another bundle in the OSGi container actually does, does it create a new instance or does it give you a pointer to the instance that is registered in the container?

Are there any dangers in using the service instance after the service has been stopped?


Solution

  • This is a very good question so I digged into the specification in search for a definitive answer. It turns out that there is a whole section talking about this problem - see section 5.4 Stale References starting on page 132 of OSGi Service Platform Core Specification, Release 4, Version 4.2.

    To answer your question according to the specification:

    The behavior of a service that becomes unregistered is undefined. Such services may continue to work properly or throw an exception at their discretion.

    And to prevent potential problems:

    Bundles must listen to events generated by the Framework to clean up and remove stale references.

    The specification also gives some tips how to minimize the consequences of stale references.