FELIX-5199 Race condition in HttpServiceFactory.getService() causing exception

Improved the thread safety of this fix.


git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@1732453 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/http/base/src/main/java/org/apache/felix/http/base/internal/service/HttpServiceFactory.java b/http/base/src/main/java/org/apache/felix/http/base/internal/service/HttpServiceFactory.java
index 5bf81b7..503c476 100644
--- a/http/base/src/main/java/org/apache/felix/http/base/internal/service/HttpServiceFactory.java
+++ b/http/base/src/main/java/org/apache/felix/http/base/internal/service/HttpServiceFactory.java
@@ -139,14 +139,27 @@
     @Override
     public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> reg)
     {
-        if ( active ) {
-            return new PerBundleHttpServiceImpl(bundle,
-                    this.sharedHttpService,
-                    this.context,
-                    this.contextAttributeListenerManager,
-                    this.sharedContextAttributes,
-                    this.requestListenerManager,
-                    this.requestAttributeListenerManager);
+        // Only return a service after start() has been called.
+        if (active) {
+            // Store everything that we want to pass to the PerBundleHttpServiceImpl in local vars to avoid
+            // a race condition where the service might be stopped while this method is executing.
+            SharedHttpServiceImpl sharedHttpSvc = this.sharedHttpService;
+            ServletContext servletCtx = this.context;
+            ServletContextAttributeListenerManager servletCtxAttrListenerMgr = this.contextAttributeListenerManager;
+            boolean sharedCtxAttrs = this.sharedContextAttributes;
+            ServletRequestListenerManager reqListenerMgr = this.requestListenerManager;
+            ServletRequestAttributeListenerManager reqAttrListenerMgr = this.requestAttributeListenerManager;
+
+            if ( active ) {
+                // Only return the service if we're still active
+                return new PerBundleHttpServiceImpl(bundle,
+                        sharedHttpSvc,
+                        servletCtx,
+                        servletCtxAttrListenerMgr,
+                        sharedCtxAttrs,
+                        reqListenerMgr,
+                        reqAttrListenerMgr);
+            }
         }
         return null;
     }