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?
The reference element is used to refer to a service in the OSGi service registry, and is independent of how that service was registered.
OSGi gives you a separate class-loader for each service which is not possible in a singleton. All {singleton} classes are loaded by a single classloader. We can't have two classes with the same name (fully qualified name) in a singleton but this is possible in OSGi.
"Components" are less formally defined than services. A service is any object that is registered in the OSGi Service Registry and can be looked up using its interface name(s). The only prerequisite is that a service should implement some interface... any interface.
An OSGi service is a Java class or service interface, along with a number of service properties as name/value pairs. The service properties differentiate among different service providers that provide services with the same service interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With