PedroD
PedroD

Reputation: 6043

Why do we return a service instance in the addingService(ServiceReference reference) method?

In several books they say that it is a good practice to unget all getted services, but in every example I see of the servicetracker implementation has this method defined like this:

@Override
  public Object addingService(ServiceReference reference) {
    IQuoteService service = (IQuoteService) context.getService(reference);
    /* some stuff */
    return service;
  }

And they return the service instance... How do I know/guarantee that the instance returned by this method will ever be ungetted?

Upvotes: 0

Views: 63

Answers (1)

Balazs Zsoldos
Balazs Zsoldos

Reputation: 6046

See the source and javadoc of ServiceTracker and ServiceTrackerCustomizer. The default implementation calls unget in the removedService(...) function:

http://grepcode.com/file/repo1.maven.org/maven2/org.osgi/org.osgi.compendium/4.3.1/org/osgi/util/tracker/ServiceTracker.java#493

You should implement that funciton in the same way in your ServiceTrackerCustomizer (or an inherited ServiceTracker).

However, ServiceTracker is low-level API. You need it only if your use-case cannot be solved with Felix SCR or any of its alternatives.

Upvotes: 3

Related Questions