OsgiWhiteboard implements Whiteboard { @Override public <T> Registration register( final Class<T> type, final T service, Map<?, ?> properties) { checkNotNull(type); checkNotNull(service); checkNotNull(properties); checkArgument(type.isInstance(service)); Dictionary<Object, Object> dictionary = new Hashtable<Object, Object>(); for (Map.Entry<?, ?> entry : properties.entrySet()) { dictionary.put(entry.getKey(), entry.getValue()); } final ServiceRegistration registration = context.registerService(type.getName(), service, dictionary); return new Registration() { private volatile boolean unregistered; @Override public void unregister() { try { if (!unregistered) { registration.unregister(); unregistered = true; } else { log.warn("Service {} of type {} unregistered multiple times", service, type); } } catch (IllegalStateException ex) { log.warn("Error unregistering service: {} of type {}", service, type.getName(), ex); } } }; } OsgiWhiteboard(@NotNull BundleContext context); @Override Registration register(
            final Class<T> type, final T service, Map<?, ?> properties); @Override Tracker<T> track(final Class<T> type); @Override Tracker<T> track(Class<T> type, Map<String, String> filterProperties);  }
@Test public void testDoubleUnregister() { BundleContext bundleContext = mock(BundleContext.class); OsgiWhiteboard w = new OsgiWhiteboard(bundleContext); Runnable r = new Runnable() { @Override public void run() { } }; final AtomicBoolean unregistered = new AtomicBoolean(); ServiceRegistration sr = new ServiceRegistration() { @Override public void unregister() { if (unregistered.get()) { throw new IllegalStateException( "Service already unregistered."); } unregistered.set(true); } @Override public void setProperties(Dictionary properties) { } @Override public ServiceReference getReference() { return null; } }; when( bundleContext.registerService(Runnable.class.getName(), r, new Hashtable<Object, Object>())).thenReturn(sr); Registration reg = w.register(Runnable.class, r, new HashMap<String, Object>()); reg.unregister(); assertTrue(unregistered.get()); reg.unregister(); }