You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by an...@apache.org on 2017/03/03 20:11:35 UTC

[1/2] tomee git commit: Release WebBeansContext later & check for nulls

Repository: tomee
Updated Branches:
  refs/heads/tomee-1.7.x fdadd4fa8 -> 39b42eb63


Release WebBeansContext later & check for nulls


Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/ffea29dd
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/ffea29dd
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/ffea29dd

Branch: refs/heads/tomee-1.7.x
Commit: ffea29dda5c7cd85ad3f06bf00bf351edfab6f53
Parents: fdadd4f
Author: AndyGee <an...@gmx.de>
Authored: Fri Mar 3 21:09:54 2017 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Fri Mar 3 21:09:54 2017 +0100

----------------------------------------------------------------------
 .../openejb/assembler/classic/Assembler.java    | 135 ++++++++++++-------
 1 file changed, 85 insertions(+), 50 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/tomee/blob/ffea29dd/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java b/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
index 46ff758..eceb615 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
@@ -556,7 +556,12 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
             rIds.add(resourceInfo.id);
         }
         rIds.removeAll(reservedResourceIds);
-        postConstructResources(rIds, ParentClassLoaderFinder.Helper.get(), systemInstance.getComponent(ContainerSystem.class).getJNDIContext(), null);
+        final ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);
+        if (containerSystem != null) {
+            postConstructResources(rIds, ParentClassLoaderFinder.Helper.get(), containerSystem.getJNDIContext(), null);
+        }else {
+            logger.error("ContainerSystem not initialized");
+        }
 
         // Containers
         for (final ContainerInfo serviceInfo : containerSystemInfo.containers) {
@@ -805,7 +810,9 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
 
             if (start) {
                 final EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class);
-                globalEjbResolver.addAll(appInfo.ejbJars);
+                if (globalEjbResolver != null) {
+                    globalEjbResolver.addAll(appInfo.ejbJars);
+                }
             }
 
             // bind all global values on global context
@@ -1777,11 +1784,11 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
 
             try {
                 timeout = Integer.parseInt(SystemInstance.get().getProperty(TOMEE_DATASOURCE_DESTROY_TIMEOUT, "1000"));
-                if(timeout < 50){
+                if (timeout < 50) {
                     logger.warning(TOMEE_DATASOURCE_DESTROY_TIMEOUT + " must be at least 50");
                     timeout = 50;
                 }
-                if(timeout > 30000){
+                if (timeout > 30000) {
                     timeout = 30000;
                     logger.warning(TOMEE_DATASOURCE_DESTROY_TIMEOUT + " must not be greater than 30000");
                 }
@@ -1915,46 +1922,36 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
             deployedApplications.remove(appInfo.path);
             logger.info("destroyApplication.start", appInfo.path);
 
-            final Context globalContext = containerSystem.getJNDIContext();
             final AppContext appContext = containerSystem.getAppContext(appInfo.appId);
-            final ClassLoader classLoader = appContext.getClassLoader();
-
-            SystemInstance.get().fireEvent(new AssemblerBeforeApplicationDestroyed(appInfo, appContext));
 
             if (null == appContext) {
                 logger.warning("Application id '" + appInfo.appId + "' not found in: " + Arrays.toString(containerSystem.getAppContextKeys()));
                 return;
-            } else {
-                final WebBeansContext webBeansContext = appContext.getWebBeansContext();
-                if (webBeansContext != null) {
-                    final ClassLoader old = Thread.currentThread().getContextClassLoader();
-                    Thread.currentThread().setContextClassLoader(classLoader);
-                    try {
-                        webBeansContext.getService(ContainerLifecycle.class).stopApplication(null);
-                    } finally {
-                        Thread.currentThread().setContextClassLoader(old);
-                    }
-                }
-                final Map<String, Object> cb = appContext.getBindings();
-                for (final Entry<String, Object> value : cb.entrySet()) {
-                    String path = value.getKey();
-                    if (path.startsWith("global")) {
-                        path = "java:" + path;
-                    }
-                    if (!path.startsWith("java:global")) {
-                        continue;
-                    }
+            }
+
+            final Context globalContext = containerSystem.getJNDIContext();
+            SystemInstance.get().fireEvent(new AssemblerBeforeApplicationDestroyed(appInfo, appContext));
 
-                    unbind(globalContext, path);
-                    unbind(globalContext, "openejb/global/" + path.substring("java:".length()));
-                    unbind(globalContext, path.substring("java:global".length()));
+            final Map<String, Object> cb = appContext.getBindings();
+            for (final Entry<String, Object> value : cb.entrySet()) {
+                String path = value.getKey();
+                if (path.startsWith("global")) {
+                    path = "java:" + path;
                 }
-                if (appInfo.appId != null && !appInfo.appId.isEmpty() && !"openejb".equals(appInfo.appId)) {
-                    unbind(globalContext, "global/" + appInfo.appId);
-                    unbind(globalContext, appInfo.appId);
+                if (!path.startsWith("java:global")) {
+                    continue;
                 }
+
+                unbind(globalContext, path);
+                unbind(globalContext, "openejb/global/" + path.substring("java:".length()));
+                unbind(globalContext, path.substring("java:global".length()));
+            }
+            if (appInfo.appId != null && !appInfo.appId.isEmpty() && !"openejb".equals(appInfo.appId)) {
+                unbind(globalContext, "global/" + appInfo.appId);
+                unbind(globalContext, appInfo.appId);
             }
 
+
             final EjbResolver globalResolver = new EjbResolver(null, EjbResolver.Scope.GLOBAL);
             for (final AppInfo info : deployedApplications.values()) {
                 globalResolver.addAll(info.ejbJars);
@@ -2000,11 +1997,11 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
             Collections.reverse(deployments);
 
             // Stop
-            for (final BeanContext deployment : deployments) {
-                final String deploymentID = String.valueOf(deployment.getDeploymentID());
+            for (final BeanContext bc : deployments) {
+                final String deploymentID = String.valueOf(bc.getDeploymentID());
                 try {
-                    final Container container = deployment.getContainer();
-                    container.stop(deployment);
+                    final Container container = bc.getContainer();
+                    container.stop(bc);
                 } catch (final Throwable t) {
                     undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                 }
@@ -2047,6 +2044,8 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
             for (final WebContext webContext : appContext.getWebContexts()) {
                 containerSystem.removeWebContext(webContext);
             }
+
+            final ClassLoader classLoader = appContext.getClassLoader();
             TldScanner.forceCompleteClean(classLoader);
 
             // Clear out naming for all components first
@@ -2214,6 +2213,17 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
                 }
             }
 
+            final WebBeansContext webBeansContext = appContext.getWebBeansContext();
+            if (webBeansContext != null) {
+                final ClassLoader old = Thread.currentThread().getContextClassLoader();
+                Thread.currentThread().setContextClassLoader(classLoader);
+                try {
+                    webBeansContext.getService(ContainerLifecycle.class).stopApplication(null);
+                } finally {
+                    Thread.currentThread().setContextClassLoader(old);
+                }
+            }
+
             containerSystem.removeAppContext(appInfo.appId);
 
             if (!appInfo.properties.containsKey("tomee.destroying")) { // destroy tomee classloader after resources cleanup
@@ -2264,26 +2274,26 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
         // to be instantiated
         final String ctx = name.substring(0, name.lastIndexOf("/"));
         final String objName = name.substring(ctx.length() + 1);
-        
+
         final NamingEnumeration<Binding> bindings = globalContext.listBindings(ctx);
         while (bindings.hasMoreElements()) {
             final Binding binding = bindings.nextElement();
             if (!binding.getName().equals(objName)) {
                 continue;
             }
-            
+
             if (!LazyObjectReference.class.isInstance(binding.getObject())) {
                 continue;
             }
-            
+
             final LazyObjectReference<?> ref = LazyObjectReference.class.cast(binding.getObject());
-            if (! ref.isInitialized()) {
+            if (!ref.isInitialized()) {
                 globalContext.unbind(name);
                 removeResourceInfo(id);
                 return;
             }
         }
-        
+
         // otherwise, look the object up and remove it
         final Object object = globalContext.lookup(name);
         final String clazz;
@@ -2337,7 +2347,10 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
                 logger.warning("Failed to find open-jpa-integration jar");
             }
         }
-        jars.addAll(Arrays.asList(SystemInstance.get().getComponent(ClassLoaderEnricher.class).applicationEnrichment()));
+        final ClassLoaderEnricher component = SystemInstance.get().getComponent(ClassLoaderEnricher.class);
+        if (component != null) {
+            jars.addAll(Arrays.asList(component.applicationEnrichment()));
+        }
 
         // Create the class loader
         final ClassLoader parent = ParentClassLoaderFinder.Helper.get();
@@ -3168,7 +3181,10 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
             }
 
             if (logger == null) {
-                logger = SystemInstance.get().getComponent(Assembler.class).logger;
+                final Assembler a = SystemInstance.get().getComponent(Assembler.class);
+                if (a != null) {
+                    logger = a.logger;
+                }
             }
             unusedProperty(info.id, logger, property);
         }
@@ -3254,7 +3270,10 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
                     transformers.add(classFileTransformer);
                 }
             } else if (!logged.getAndSet(true)) {
-                SystemInstance.get().getComponent(Assembler.class).getLogger().warning("assembler.noAgent");
+                final Assembler a = SystemInstance.get().getComponent(Assembler.class);
+                if (a != null) {
+                    a.getLogger().warning("assembler.noAgent");
+                }
             }
         }
 
@@ -3268,7 +3287,10 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
                         instrumentation.removeTransformer(transformer);
                     }
                 } else {
-                    SystemInstance.get().getComponent(Assembler.class).getLogger().error("assembler.noAgent");
+                    final Assembler a = SystemInstance.get().getComponent(Assembler.class);
+                    if (a != null) {
+                        a.getLogger().error("assembler.noAgent");
+                    }
                 }
             }
         }
@@ -3357,10 +3379,15 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
 
         protected Object readResolve() throws ObjectStreamException {
             try {
-                return SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(jndi);
+                final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
+                if (containerSystem != null) {
+                    return containerSystem.getJNDIContext().lookup(jndi);
+                }
             } catch (final Exception e) {
                 throw new InvalidObjectException("name not found: " + jndi);
             }
+
+            return null;
         }
     }
 
@@ -3406,7 +3433,10 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
                     }
                     m.invoke(o);
                 } catch (final Exception e) {
-                    SystemInstance.get().getComponent(Assembler.class).getLogger().error(e.getMessage(), e);
+                    final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
+                    if (assembler != null) {
+                        assembler.getLogger().error(e.getMessage(), e);
+                    }
                 }
             }
             try {
@@ -3422,10 +3452,15 @@ public class Assembler extends AssemblerTool implements org.apache.openejb.spi.A
         // which is never serialized (IvmContext)
         Object readResolve() throws ObjectStreamException {
             try {
-                return SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(name);
+                final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
+                if (containerSystem != null) {
+                    return containerSystem.getJNDIContext().lookup(name);
+                }
             } catch (final NamingException e) {
                 throw new IllegalStateException(e);
             }
+
+            return null;
         }
     }
 }


Fwd: [1/2] tomee git commit: Release WebBeansContext later & check for nulls

Posted by Romain Manni-Bucau <rm...@gmail.com>.
Quick note to say that most of these null checks are useless cause you cant
enter this code if null. This is false postives of your ide i guess. (No
need to fix but dont listen the ide please)
---------- Message transféré ----------
De : <an...@apache.org>
Date : 3 mars 2017 21:11
Objet : [1/2] tomee git commit: Release WebBeansContext later & check for
nulls
À : <co...@tomee.apache.org>
Cc :

Repository: tomee
> Updated Branches:
>   refs/heads/tomee-1.7.x fdadd4fa8 -> 39b42eb63
>
>
> Release WebBeansContext later & check for nulls
>
>
> Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
> Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/ffea29dd
> Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/ffea29dd
> Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/ffea29dd
>
> Branch: refs/heads/tomee-1.7.x
> Commit: ffea29dda5c7cd85ad3f06bf00bf351edfab6f53
> Parents: fdadd4f
> Author: AndyGee <an...@gmx.de>
> Authored: Fri Mar 3 21:09:54 2017 +0100
> Committer: AndyGee <an...@gmx.de>
> Committed: Fri Mar 3 21:09:54 2017 +0100
>
> ----------------------------------------------------------------------
>  .../openejb/assembler/classic/Assembler.java    | 135 ++++++++++++-------
>  1 file changed, 85 insertions(+), 50 deletions(-)
> ----------------------------------------------------------------------
>
>
> http://git-wip-us.apache.org/repos/asf/tomee/blob/ffea29dd/
> container/openejb-core/src/main/java/org/apache/openejb/
> assembler/classic/Assembler.java
> ----------------------------------------------------------------------
> diff --git a/container/openejb-core/src/main/java/org/apache/openejb/
> assembler/classic/Assembler.java b/container/openejb-core/src/
> main/java/org/apache/openejb/assembler/classic/Assembler.java
> index 46ff758..eceb615 100644
> --- a/container/openejb-core/src/main/java/org/apache/openejb/
> assembler/classic/Assembler.java
> +++ b/container/openejb-core/src/main/java/org/apache/openejb/
> assembler/classic/Assembler.java
> @@ -556,7 +556,12 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>              rIds.add(resourceInfo.id);
>          }
>          rIds.removeAll(reservedResourceIds);
> -        postConstructResources(rIds, ParentClassLoaderFinder.Helper.get(),
> systemInstance.getComponent(ContainerSystem.class).getJNDIContext(),
> null);
> +        final ContainerSystem containerSystem =
> systemInstance.getComponent(ContainerSystem.class);
> +        if (containerSystem != null) {
> +            postConstructResources(rIds, ParentClassLoaderFinder.Helper.get(),
> containerSystem.getJNDIContext(), null);
> +        }else {
> +            logger.error("ContainerSystem not initialized");
> +        }
>
>          // Containers
>          for (final ContainerInfo serviceInfo : containerSystemInfo.containers)
> {
> @@ -805,7 +810,9 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>
>              if (start) {
>                  final EjbResolver globalEjbResolver =
> systemInstance.getComponent(EjbResolver.class);
> -                globalEjbResolver.addAll(appInfo.ejbJars);
> +                if (globalEjbResolver != null) {
> +                    globalEjbResolver.addAll(appInfo.ejbJars);
> +                }
>              }
>
>              // bind all global values on global context
> @@ -1777,11 +1784,11 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>
>              try {
>                  timeout = Integer.parseInt(SystemInstance.get().
> getProperty(TOMEE_DATASOURCE_DESTROY_TIMEOUT, "1000"));
> -                if(timeout < 50){
> +                if (timeout < 50) {
>                      logger.warning(TOMEE_DATASOURCE_DESTROY_TIMEOUT + "
> must be at least 50");
>                      timeout = 50;
>                  }
> -                if(timeout > 30000){
> +                if (timeout > 30000) {
>                      timeout = 30000;
>                      logger.warning(TOMEE_DATASOURCE_DESTROY_TIMEOUT + "
> must not be greater than 30000");
>                  }
> @@ -1915,46 +1922,36 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>              deployedApplications.remove(appInfo.path);
>              logger.info("destroyApplication.start", appInfo.path);
>
> -            final Context globalContext = containerSystem.
> getJNDIContext();
>              final AppContext appContext = containerSystem.getAppContext(
> appInfo.appId);
> -            final ClassLoader classLoader = appContext.getClassLoader();
> -
> -            SystemInstance.get().fireEvent(new
> AssemblerBeforeApplicationDestroyed(appInfo, appContext));
>
>              if (null == appContext) {
>                  logger.warning("Application id '" + appInfo.appId + "'
> not found in: " + Arrays.toString(containerSystem.getAppContextKeys()));
>                  return;
> -            } else {
> -                final WebBeansContext webBeansContext =
> appContext.getWebBeansContext();
> -                if (webBeansContext != null) {
> -                    final ClassLoader old = Thread.currentThread().
> getContextClassLoader();
> -                    Thread.currentThread().setContextClassLoader(
> classLoader);
> -                    try {
> -                        webBeansContext.getService(
> ContainerLifecycle.class).stopApplication(null);
> -                    } finally {
> -                        Thread.currentThread().
> setContextClassLoader(old);
> -                    }
> -                }
> -                final Map<String, Object> cb = appContext.getBindings();
> -                for (final Entry<String, Object> value : cb.entrySet()) {
> -                    String path = value.getKey();
> -                    if (path.startsWith("global")) {
> -                        path = "java:" + path;
> -                    }
> -                    if (!path.startsWith("java:global")) {
> -                        continue;
> -                    }
> +            }
> +
> +            final Context globalContext = containerSystem.
> getJNDIContext();
> +            SystemInstance.get().fireEvent(new
> AssemblerBeforeApplicationDestroyed(appInfo, appContext));
>
> -                    unbind(globalContext, path);
> -                    unbind(globalContext, "openejb/global/" +
> path.substring("java:".length()));
> -                    unbind(globalContext, path.substring("java:global".
> length()));
> +            final Map<String, Object> cb = appContext.getBindings();
> +            for (final Entry<String, Object> value : cb.entrySet()) {
> +                String path = value.getKey();
> +                if (path.startsWith("global")) {
> +                    path = "java:" + path;
>                  }
> -                if (appInfo.appId != null && !appInfo.appId.isEmpty() &&
> !"openejb".equals(appInfo.appId)) {
> -                    unbind(globalContext, "global/" + appInfo.appId);
> -                    unbind(globalContext, appInfo.appId);
> +                if (!path.startsWith("java:global")) {
> +                    continue;
>                  }
> +
> +                unbind(globalContext, path);
> +                unbind(globalContext, "openejb/global/" +
> path.substring("java:".length()));
> +                unbind(globalContext, path.substring("java:global".
> length()));
> +            }
> +            if (appInfo.appId != null && !appInfo.appId.isEmpty() &&
> !"openejb".equals(appInfo.appId)) {
> +                unbind(globalContext, "global/" + appInfo.appId);
> +                unbind(globalContext, appInfo.appId);
>              }
>
> +
>              final EjbResolver globalResolver = new EjbResolver(null,
> EjbResolver.Scope.GLOBAL);
>              for (final AppInfo info : deployedApplications.values()) {
>                  globalResolver.addAll(info.ejbJars);
> @@ -2000,11 +1997,11 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>              Collections.reverse(deployments);
>
>              // Stop
> -            for (final BeanContext deployment : deployments) {
> -                final String deploymentID = String.valueOf(deployment.
> getDeploymentID());
> +            for (final BeanContext bc : deployments) {
> +                final String deploymentID = String.valueOf(bc.
> getDeploymentID());
>                  try {
> -                    final Container container = deployment.getContainer();
> -                    container.stop(deployment);
> +                    final Container container = bc.getContainer();
> +                    container.stop(bc);
>                  } catch (final Throwable t) {
>                      undeployException.getCauses().add(new
> Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
>                  }
> @@ -2047,6 +2044,8 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>              for (final WebContext webContext :
> appContext.getWebContexts()) {
>                  containerSystem.removeWebContext(webContext);
>              }
> +
> +            final ClassLoader classLoader = appContext.getClassLoader();
>              TldScanner.forceCompleteClean(classLoader);
>
>              // Clear out naming for all components first
> @@ -2214,6 +2213,17 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>                  }
>              }
>
> +            final WebBeansContext webBeansContext =
> appContext.getWebBeansContext();
> +            if (webBeansContext != null) {
> +                final ClassLoader old = Thread.currentThread().
> getContextClassLoader();
> +                Thread.currentThread().setContextClassLoader(
> classLoader);
> +                try {
> +                    webBeansContext.getService(ContainerLifecycle.class).
> stopApplication(null);
> +                } finally {
> +                    Thread.currentThread().setContextClassLoader(old);
> +                }
> +            }
> +
>              containerSystem.removeAppContext(appInfo.appId);
>
>              if (!appInfo.properties.containsKey("tomee.destroying")) {
> // destroy tomee classloader after resources cleanup
> @@ -2264,26 +2274,26 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>          // to be instantiated
>          final String ctx = name.substring(0, name.lastIndexOf("/"));
>          final String objName = name.substring(ctx.length() + 1);
> -
> +
>          final NamingEnumeration<Binding> bindings =
> globalContext.listBindings(ctx);
>          while (bindings.hasMoreElements()) {
>              final Binding binding = bindings.nextElement();
>              if (!binding.getName().equals(objName)) {
>                  continue;
>              }
> -
> +
>              if (!LazyObjectReference.class.isInstance(binding.getObject()))
> {
>                  continue;
>              }
> -
> +
>              final LazyObjectReference<?> ref = LazyObjectReference.class.
> cast(binding.getObject());
> -            if (! ref.isInitialized()) {
> +            if (!ref.isInitialized()) {
>                  globalContext.unbind(name);
>                  removeResourceInfo(id);
>                  return;
>              }
>          }
> -
> +
>          // otherwise, look the object up and remove it
>          final Object object = globalContext.lookup(name);
>          final String clazz;
> @@ -2337,7 +2347,10 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>                  logger.warning("Failed to find open-jpa-integration jar");
>              }
>          }
> -        jars.addAll(Arrays.asList(SystemInstance.get().getComponent(
> ClassLoaderEnricher.class).applicationEnrichment()));
> +        final ClassLoaderEnricher component = SystemInstance.get().
> getComponent(ClassLoaderEnricher.class);
> +        if (component != null) {
> +            jars.addAll(Arrays.asList(component.
> applicationEnrichment()));
> +        }
>
>          // Create the class loader
>          final ClassLoader parent = ParentClassLoaderFinder.Helper.get();
> @@ -3168,7 +3181,10 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>              }
>
>              if (logger == null) {
> -                logger = SystemInstance.get().
> getComponent(Assembler.class).logger;
> +                final Assembler a = SystemInstance.get().
> getComponent(Assembler.class);
> +                if (a != null) {
> +                    logger = a.logger;
> +                }
>              }
>              unusedProperty(info.id, logger, property);
>          }
> @@ -3254,7 +3270,10 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>                      transformers.add(classFileTransformer);
>                  }
>              } else if (!logged.getAndSet(true)) {
> -                SystemInstance.get().getComponent(Assembler.class).
> getLogger().warning("assembler.noAgent");
> +                final Assembler a = SystemInstance.get().
> getComponent(Assembler.class);
> +                if (a != null) {
> +                    a.getLogger().warning("assembler.noAgent");
> +                }
>              }
>          }
>
> @@ -3268,7 +3287,10 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>                          instrumentation.removeTransformer(transformer);
>                      }
>                  } else {
> -                    SystemInstance.get().getComponent(Assembler.class).
> getLogger().error("assembler.noAgent");
> +                    final Assembler a = SystemInstance.get().
> getComponent(Assembler.class);
> +                    if (a != null) {
> +                        a.getLogger().error("assembler.noAgent");
> +                    }
>                  }
>              }
>          }
> @@ -3357,10 +3379,15 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>
>          protected Object readResolve() throws ObjectStreamException {
>              try {
> -                return SystemInstance.get().getComponent(ContainerSystem.
> class).getJNDIContext().lookup(jndi);
> +                final ContainerSystem containerSystem =
> SystemInstance.get().getComponent(ContainerSystem.class);
> +                if (containerSystem != null) {
> +                    return containerSystem.getJNDIContext().lookup(jndi);
> +                }
>              } catch (final Exception e) {
>                  throw new InvalidObjectException("name not found: " +
> jndi);
>              }
> +
> +            return null;
>          }
>      }
>
> @@ -3406,7 +3433,10 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>                      }
>                      m.invoke(o);
>                  } catch (final Exception e) {
> -                    SystemInstance.get().getComponent(Assembler.class).
> getLogger().error(e.getMessage(), e);
> +                    final Assembler assembler = SystemInstance.get().
> getComponent(Assembler.class);
> +                    if (assembler != null) {
> +                        assembler.getLogger().error(e.getMessage(), e);
> +                    }
>                  }
>              }
>              try {
> @@ -3422,10 +3452,15 @@ public class Assembler extends AssemblerTool
> implements org.apache.openejb.spi.A
>          // which is never serialized (IvmContext)
>          Object readResolve() throws ObjectStreamException {
>              try {
> -                return SystemInstance.get().getComponent(ContainerSystem.
> class).getJNDIContext().lookup(name);
> +                final ContainerSystem containerSystem =
> SystemInstance.get().getComponent(ContainerSystem.class);
> +                if (containerSystem != null) {
> +                    return containerSystem.getJNDIContext().lookup(name);
> +                }
>              } catch (final NamingException e) {
>                  throw new IllegalStateException(e);
>              }
> +
> +            return null;
>          }
>      }
>  }
>
>

[2/2] tomee git commit: Backport pool start/stop

Posted by an...@apache.org.
Backport pool start/stop


Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/39b42eb6
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/39b42eb6
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/39b42eb6

Branch: refs/heads/tomee-1.7.x
Commit: 39b42eb633d2d59a484c7ea78200698c3c6d56e5
Parents: ffea29d
Author: AndyGee <an...@gmx.de>
Authored: Fri Mar 3 21:11:07 2017 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Fri Mar 3 21:11:07 2017 +0100

----------------------------------------------------------------------
 .../main/java/org/apache/openejb/util/Pool.java | 51 ++++++++++++++------
 .../java/org/apache/openejb/util/PoolTest.java  |  1 +
 2 files changed, 38 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/tomee/blob/39b42eb6/container/openejb-core/src/main/java/org/apache/openejb/util/Pool.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/util/Pool.java b/container/openejb-core/src/main/java/org/apache/openejb/util/Pool.java
index 1e6895e..f87fd52 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/util/Pool.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/util/Pool.java
@@ -31,6 +31,7 @@ import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.RejectedExecutionHandler;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
@@ -43,6 +44,7 @@ import java.util.logging.Level;
 import java.util.logging.Logger;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
 
 /**
  * Any successful pop() call requires a corresponding push() or discard() call.
@@ -74,6 +76,7 @@ public class Pool<T> {
 
     private final Supplier<T> supplier;
     private final AtomicReference<ScheduledExecutorService> scheduler = new AtomicReference<ScheduledExecutorService>();
+    private final AtomicReference<ScheduledFuture<?>> future = new AtomicReference<ScheduledFuture<?>>();
     private final Sweeper sweeper;
 
     private final CountingLatch out = new CountingLatch();
@@ -127,21 +130,41 @@ public class Pool<T> {
     }
 
     public Pool start() {
-        final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new SchedulerThreadFactory());
-
-        if (this.scheduler.compareAndSet(null, scheduledExecutorService)) {
-            this.scheduler.get().scheduleAtFixedRate(sweeper, 0, this.sweepInterval, MILLISECONDS);
+        ScheduledExecutorService scheduledExecutorService = this.scheduler.get();
+        boolean createdSES = scheduledExecutorService == null;
+        if (scheduledExecutorService == null) {
+            scheduledExecutorService = Executors.newScheduledThreadPool(1, new SchedulerThreadFactory());
+            if (!this.scheduler.compareAndSet(null, scheduledExecutorService)) {
+                scheduledExecutorService.shutdownNow();
+                scheduledExecutorService = this.scheduler.get();
+                createdSES = false;
+            }
+        }
+        final ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(sweeper, 0, this.sweepInterval, MILLISECONDS);
+        if (!this.future.compareAndSet(null, scheduledFuture)) {
+            scheduledFuture.cancel(true);
+        }
+        if (!createdSES) {
+            // we don't want to shutdown it, we'll just stop the task
+            this.scheduler.set(null);
         }
         return this;
     }
 
     public void stop() {
-        final ScheduledExecutorService scheduler = this.scheduler.get();
-        if (scheduler != null && this.scheduler.compareAndSet(scheduler, null)) {
+        final ScheduledFuture<?> future = this.future.getAndSet(null);
+        if (future != null
+                && !future.isDone() && !future.isCancelled()
+                && !future.cancel(false)) {
+            Logger.getLogger(Pool.class.getName()).log(Level.WARNING, "Pool scheduler task termination timeout expired");
+        }
+
+        final ScheduledExecutorService scheduler = this.scheduler.getAndSet(null);
+        if (scheduler != null) {
             scheduler.shutdown();
             try {
-                if (!scheduler.awaitTermination(10000, MILLISECONDS)) {
-                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Pool scheduler termination timeout expired");
+                if (!scheduler.awaitTermination(10, SECONDS)) { // should last something like 0s max since we killed the task
+                    Logger.getLogger(Pool.class.getName()).log(Level.WARNING, "Pool scheduler termination timeout expired");
                 }
             } catch (final InterruptedException e) {
                 //Ignore
@@ -150,7 +173,7 @@ public class Pool<T> {
     }
 
     public boolean running() {
-        return this.scheduler.get() != null;
+        return this.future.get() != null;
     }
 
     private Executor createExecutor() {
@@ -444,6 +467,9 @@ public class Pool<T> {
 
     public boolean close(final long timeout, final TimeUnit unit) throws InterruptedException {
 
+        // Stop the sweeper thread
+        stop();
+
         // drain all keys so no new instances will be accepted into the pool
         while (instances.tryAcquire()) {
             Thread.yield();
@@ -461,9 +487,6 @@ public class Pool<T> {
             //Ignore
         }
 
-        // Stop the sweeper thread
-        stop();
-
         // Drain all leases
         if (!(available instanceof Overdraft)) {
             while (available.tryAcquire()) {
@@ -659,7 +682,7 @@ public class Pool<T> {
                 while (true) {
                     final Entry entry = pop(0, MILLISECONDS, false);
                     if (entry == null) {
-                        push(entry, true);
+                        push(null, true);
                         break;
                     }
                     entries.add(entry);
@@ -771,7 +794,7 @@ public class Pool<T> {
             }
 
             for (int i = 0; i < replace.size(); i++) {
-                final long offset = maxAge > 0 ? (long) (maxAge / replace.size() * i * maxAgeOffset) % maxAge : 0l;
+                final long offset = maxAge > 0 ? (long) (maxAge / replace.size() * i * maxAgeOffset) % maxAge : 0L;
                 executor.execute(new Replace(replace.get(i).entry, offset));
             }
         }

http://git-wip-us.apache.org/repos/asf/tomee/blob/39b42eb6/container/openejb-core/src/test/java/org/apache/openejb/util/PoolTest.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/util/PoolTest.java b/container/openejb-core/src/test/java/org/apache/openejb/util/PoolTest.java
index 6dc08cd..fbde94f 100644
--- a/container/openejb-core/src/test/java/org/apache/openejb/util/PoolTest.java
+++ b/container/openejb-core/src/test/java/org/apache/openejb/util/PoolTest.java
@@ -321,6 +321,7 @@ public class PoolTest extends TestCase {
 
         final long start = System.currentTimeMillis();
         assertTrue(pool.close(10, TimeUnit.SECONDS));
+        assertFalse(pool.running());
         final long time = System.currentTimeMillis() - start;
 
         // All instances should have been removed