Java Reference
In-Depth Information
If you're using version 0.4 or higher, then there's nothing that you need to
do. If, on the other hand, you're using, or might need to use, an older version
of the proxy bundle and are relying on default equality, you'll need to pro-
vide your own implementation of
equals()
and
hashCode()
—adding these
also documents the fact that you rely on the default behavior for anyone else
maintaining your code, which is a good thing too.
You've got one little change to make for your cache to work. Remember that
OSG
i is
dynamic (we might have mentioned that once or twice already!). Bundle startup order
isn't deterministic, and so the collection of references may be populated before it's
injected into the
OfferAggregator
, or after. If the list is populated first, then the
bind()
method will be called when the
offers
field is still null. You've guarded against this in
the
sortOffersList()
method, so there's no risk of a
NullPointerException
from the
bind()
method. But there's a risk the
sortedOffers
field will never be initialized at all,
if all the
bind()
calls happen before the injection. Luckily, there's an easy solution,
which is to ensure you also sort when the offers are injected:
public void setOffers(List<SpecialOffer> offers) {
this.offers = offers;
sortOfferList();
}
If you build the updated bundle and drop it into your load directory, you should find
that everything works as it did before. You can test your caching by using the
OSG
i
console to stop and start the chocolate and cheese bundles. If you've got things right,
your stopped services will continue to appear and disappear appropriately from your
web page when you refresh it.
Other uses for monitoring
Caching is a nice use for reference listeners, but it's not the only one. In the case of
our example, when new special offers appear, they could be highlighted or bumped to
the top of an otherwise sorted list. Reference listeners can also act as a fail-safe when
using stateful services, as we discussed earlier. Finally, reference listeners allow you to
avoid calling a service that has gone away and blocking in the proxy, or to disable parts
of your application if a service goes away.
WARNING: DETECTING SERVICE SWAPS
If you're planning to use reference lis-
teners to detect when an injected service has been swapped out (for example,
to reconstitute a stateful service), be careful. If you're using a reference, the
bind-method
and the
unbind-method
aren't symmetric. The
bind-method
will
be called every time a new service is bound—every time the service changes.
But the
unbind-method
will only be called if a service goes away and can't
immediately be replaced—if your bean is left without a service. Only the
bind-method
, therefore, can be reliably used to detect when the service has
changed, whereas the
unbind-method
is most useful to detect periods of ser-
vice unavailability.