Skip to content

Instantly share code, notes, and snippets.

@njbartlett
Created May 8, 2012 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njbartlett/2638180 to your computer and use it in GitHub Desktop.
Save njbartlett/2638180 to your computer and use it in GitHub Desktop.
Building an index for OSGi service properties
public class IndexingTracker extends ServiceTracker {
private final ConcurrentMap<Object, ServiceReference> index = new ConcurrentHashMap<Object, ServiceReference>();
private final String keyProperty;
public IndexingTracker(BundleContext context, String serviceClass, String keyProperty) {
super(context, serviceClass, null);
this.keyProperty = keyProperty;
}
@Override
public Object addingService(ServiceReference reference) {
Object id = reference.getProperty(keyProperty);
ServiceReference existing = index.putIfAbsent(id, reference);
if (existing != null) {
// TODO: what should happen if multiple services have the same key?
}
return id;
}
@Override
public void removedService(ServiceReference reference, Object id) {
index.remove(id);
}
public ServiceReference findByKey(Object key) {
return index.get(key);
}
}
// Example use:
IndexingTracker indexer = new IndexingTracker(context, MyService.class.getName(), "ID");
indexer.open();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment