Search code examples
osgiapache-felix

ServiceTracker | Should we release service in addingService method in case of exception?


I have created a ServiceTracker with null ServiceTrackerCustomizer and overridden addingService and removedService methods.

Consider this code snippet for addingService method.

public T addingService(ServiceReference<T> reference) {
    T service = super.addingService(reference);
    try {
        // some code which may throw exception. 
    } catch (Exception ex) {
        // Let's not track if exception occurred.
        service = null;
        this.context.ungetService(reference);
    }
    return service;
}

So, is it ok to eagerly release the service in case of exception? Or we can just omit it and OSGi framework will take care of releasing the service later?

Please advise.


Solution

  • You should unget the service as you show in the question.