Is it necessary to remove service references in OSGi?

370 Views Asked by At

I am using the OSGi framework Knopflerfish, since I can now call the bundle to do something by register a service, do I need to remove the service?

Because I cannot find any way to remove the service. By checking the services in BundleContext with the length of "getAllService()" and ServiceTracker.getServices(), I can see the total number of service is increasing, even I call "ungetService(ServiceReference)".

So is it necessary to remove the service or "ungetService" is enough for that? How can I remove the service if this is necessary?

1

There are 1 best solutions below

2
On

ungetService is not the opposite of registerService, it is the opposite of getService, i.e. the call that a consumer makes.

If you register a service with the registerService method, it gives you a ServiceRegistration object back. You should call the unregister method on that object when you no longer want your service to be available to consumers. Note that if your bundle stops, any services that it registered will be automatically unregistered.

However, I wonder if you should really be digging this deep into the lowest level OSGi APIs. For 99% of use cases you should be using a higher-level framework like Declarative Services. This will save you a hell of a lot of pain, and also make your code more reliable and readable.