When using @Reference
in a service to inject references to multiple service (ReferenceCardinality.MULTIPLE
) implementations, what guarantees does OSGi make on how the injected services are ordered? Are they always ordered by service.ranking
.
Currently I do the following:
@Reference(
service = SomeInterface.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY,
fieldOption = FieldOption.UPDATE
)
private final List<SomeInterface> refs = new CopyOnWriteArrayList<>();
(annotations are OSGi R7 annotations)
When testing this, I always see the elements on list refs
in descending order of their service.ranking
but I don’t know if that’s by design or by accident and if it’s guaranteed by OSGi or not. I haven’t found a definite answer in the specifications or any blog post.
Also, does this hold when using different values for policy
, policyOption
or fieldOption
?
Since you are supplying your own list (and not letting Declarative Services (DS) supply the list), DS can only call add
and remove
on your list object. See https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html#d0e37871.
Since DS only calls your list object, your list implementation must be responsible for any desired ordering.
If you let DS supply the list, then the list will always be ordered: "sorted using the same ordering as ServiceReference.compareTo
based upon service ranking and service id". See https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html#d0e37828.