Java Reference
In-Depth Information
public interface ServiceFactory {
public Object getService(Bundle bundle,
ServiceRegistration registration);
public void ungetService(Bundle bundle,
ServiceRegistration registration, Object service);
}
The framework caches factory-created service instances, so a bundle requesting the
same service twice receives the same instance. This cached instance is removed only
when the bundle has completely finished with a service (that is, the number of calls to
get it match the calls to unget it), when the bundle has stopped, or when the service
factory is unregistered. Should you always unget a service after you use it, like closing
an I/O stream?
4.5.3
When should I unget a service?
You just saw that instances created from service factories are cached until the consum-
ing bundle has finished with the service. This is determined by counting the calls to
getService() compared to ungetService() . Forgetting to call unget can lead to
instances being kept around until the bundle is stopped. Similarly, agents interrogat-
ing the framework will assume the bundle is using the service when it isn't. Should you
always unget after using a service, perhaps something like the following?
try {
Service svc = (Service) m_context.getService(svcRef);
if (svc != null) {
svc.dispatch(something);
} else {
fallback(somethingElse);
}
} finally {
m_context.ungetService(svcRef);
}
This code records exactly when you use the service, but what happens if you want to
use it again and again in a short space of time? Services backed by factories will end up
creating and destroying a new instance on every call, which can be costly. You may also
want to keep the instance alive between calls if it contains session-related data. In
these circumstances, it makes more sense to get at the start of the session and unget at
the end of the session. For long-lived sessions, you still need to track the service in case
it's removed, probably using a service tracker customizer to close the session. In all
other situations, you should unget the service when you're finished with it.
But what about the other side of the equation? Should bundles let the framework
unregister their services when they stop, or should they be more proactive and unreg-
ister services as soon as they don't want to or can't support them?
4.5.4
When should I unregister my service?
The OSG i framework does a lot of tidying up when a bundle stops—it removes listen-
ers, releases used services, and unregisters published services. It can often feel like you
Search WWH ::




Custom Search