OSGI ServiceTracker and thread-safety
ServiceTracker is defined as a Thread-Safe class in the OSGI 4.2 spec
The usage of this class is pretty straight forward.
Most of the examples employing ServiceTracker I could find on the internet show a snippet of code like the following:
ServiceInterface serviceObj = (ServiceInterface) serviceTracker.get();
if(serviceObj != null) {
// ...
// do smth with the serviceObject
// ...
}
Now my question is: once the service implementation object is retrieved from the serviceTracker, there is no guarantee that it will be available (won't be removed) immediately after the null-check.
In other words, even within the if-cycle, the service object (serviceObj) may very well become null suddenly (if the corresponding service is unregistered)
Therefore we should always correct the code above like this:
ServiceInterface serviceObj = (ServiceInterface) serviceTracker.get();
if(serviceObj != null) {
try {
// ...
// do smth with the serviceObject
// ...
} catch(Throwable th) {
// a null-pointer exception may have occurred here!!
}
}
Despite of this, no examples either in blogs (http://developers-blog.org/blog/default/2010/03/31/OSGI-Tutorial-How-to-use-ServiceTracker-to-get-Services) or books (Osgi In Action) talk abou开发者_开发知识库t this requirement...
Am I right? Am I missing something?
You're basically correct, however the question is whether to handle the exception in your own code or to allow it to bubble up the call stack to some kind of global handler.
Most OSGi developers that I know, and myself included, prefer the approach of allowing the exception to be thrown from this level. Catching exceptions at every point that they might occur leads to horribly bloated code.
In a sense, this goes to the heart of the debate between checked and unchecked exceptions.
Note one small correction: your reference variable serviceObj
cannot become null
after the null-check since it is a local variable, and other threads can never change the value of your local variables. However, as you deduced, the service reference can become defunct or inoperative. The chances of this happening are very small though if you have only just retrieved the reference from the tracker.
精彩评论