Need to invalidate bundle context earlier too if there is an activation
failure to avoid race conditions on runaway threads adding listeners or
services. (FELIX-3082)


git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@1162178 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/framework/src/main/java/org/apache/felix/framework/Felix.java b/framework/src/main/java/org/apache/felix/framework/Felix.java
index a0d9ed4..55d3b49 100644
--- a/framework/src/main/java/org/apache/felix/framework/Felix.java
+++ b/framework/src/main/java/org/apache/felix/framework/Felix.java
@@ -2017,6 +2017,13 @@
                 // Clean up the bundle activator
                 bundle.setActivator(null);
 
+                // Clean up the bundle context.
+                // We invalidate this first to make sure it cannot be used
+                // after stopping the activator.
+                BundleContextImpl bci = (BundleContextImpl) bundle._getBundleContext();
+                bci.invalidate();
+                bundle.setBundleContext(null);
+
                 // Unregister any services offered by this bundle.
                 m_registry.unregisterServices(bundle);
 
@@ -2024,11 +2031,7 @@
                 m_registry.ungetServices(bundle);
 
                 // Remove any listeners registered by this bundle.
-                m_dispatcher.removeListeners(bundle._getBundleContext());
-
-                // Clean up the bundle context.
-                ((BundleContextImpl) bundle._getBundleContext()).invalidate();
-                bundle.setBundleContext(null);
+                m_dispatcher.removeListeners(bci);
 
                 // The spec says to expect BundleException or
                 // SecurityException, so rethrow these exceptions.