Java Reference
In-Depth Information
for (ServiceReference r : refs) {
m_logListener.serviceChanged(
new ServiceEvent(ServiceEvent.REGISTERED, r));
}
}
}
Sends
pseudo-
events
startTestThread();
}
public void stop(BundleContext context) {
m_context.removeServiceListener(m_logListener);
stopTestThread();
}
}
You deliberately lock the listener before passing it to the framework, so the pseudo-
registration events are processed first. Otherwise, it would be possible to receive an
UNREGISTERING event for a service before its pseudo-registration. Only when the lis-
tener has been added do you check for existing services, to make sure you don't miss
any intervening registrations. You could potentially end up with duplicate registra-
tions by doing the checks in this order, but that's better than missing services. The test
method now only needs to call the helper method to get the best Log Service, as
shown in the following listing.
Listing 4.12 Correct listener example—using the listener to get the best Log Service
while (Thread.currentThread() == m_logTestThread) {
LogService logService = m_logListener.getLogService();
if (logService != null) {
try {
logService.log(LogService.LOG_INFO, "ping");
} catch (RuntimeException re) {
alternativeLog("error in LogService " + re);
}
} else {
alternativeLog("LogService has gone");
}
pauseTestThread();
}
You may have noticed that the finished listener example still doesn't unget the service
after using it; this is left as an exercise for you. Here's a hint to get you started: think
about moving responsibility for logging into the listener. This will also help you
reduce the time between binding the service and using it.
Service listeners reduce the need to continually poll the service registry. They let
you react to changes in services as soon as they occur and get around the inherent
race condition of the find-then-get approach. The downside of listeners is the amount
of code you need to write. Imagine having to do this for every service you want to use
and having to repeatedly test for synchronization issues. Why doesn't OSG i provide a
 
Search WWH ::




Custom Search