0

I have this component (pseudo code):

@Component
class ServiceComponent {
  Set<MyService> set = synchronizedSet();

  @Activate
  activate(){... process set...}

  @Reference
  addService(MyService service){set.add(service)}
}

Now, initially, when the component is activated, it will have add all available instances of MyService. But how would I best handle additions after the component has been activated?

erdal.karaca
  • 693
  • 1
  • 4
  • 20

2 Answers2

0

Actually your code as written will only get a single instance of MyService, because references have a cardinality of 1..1 by default.

To bind to all instances, change the reference declaration as follows:

@Reference(cardinality = ReferenceCardinality.MULTIPLE,
           policy = ReferencePolicy.DYNAMIC)
void addService(MyService service) {
    set.add(service);
}

Bear in mind that this method can be called after or even during the activate() method.

Neil Bartlett
  • 23,743
  • 4
  • 44
  • 77
  • Yes, I know, that is why I have written it is pseudo code. Sorry for the confusion, but how to best deal with dynamic behavior of service additions/removals. I mean, I would for example use an observable list (from Eclipse JFace) to listen to the set once it changes after the component has been activated. But is there some best practices in pure OSGi? – erdal.karaca Aug 04 '16 at 20:23
  • It depends entirely what your code needs to do with this information. – Neil Bartlett Aug 04 '16 at 20:42
  • If you use an SWT/JFace observable, bear in mind that you cannot predict which thread the `addService` method will be called from. So you cannot directly update the UI from this method. You will need to use `Display.asyncExec` to make any UI changes resulting from the added service. In Swing the equivalent would be `SwingUtilities.invokeLater`. – Neil Bartlett Aug 04 '16 at 20:44
0

In the latest version of DS you can do field annotations. If you specify the field to be volatile, then it will be updated when new services enter.

 @Reference
 volatile Set<MyService>   services;
Peter Kriens
  • 15,196
  • 1
  • 37
  • 55