You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by jg...@apache.org on 2025/09/09 17:16:34 UTC

(tomee) branch main updated: TOMEE-4527 prevent ThreadContext being entered twice

This is an automated email from the ASF dual-hosted git repository.

jgallimore pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomee.git


The following commit(s) were added to refs/heads/main by this push:
     new 03c029ee5c TOMEE-4527 prevent ThreadContext being entered twice
03c029ee5c is described below

commit 03c029ee5c5ce4e870f6344d0ce87262358719c3
Author: Jonathan Gallimore <jo...@jrg.me.uk>
AuthorDate: Wed Aug 27 16:30:51 2025 +0100

    TOMEE-4527 prevent ThreadContext being entered twice
---
 .../cdi/RequestScopedThreadContextListener.java    |  48 +++-
 .../org/apache/openejb/core/ThreadContext.java     |  24 +-
 .../impl/ApplicationThreadContextProvider.java     |  21 +-
 .../openejb/threads/impl/ContextServiceImpl.java   |  31 +++
 .../impl/SecurityThreadContextProvider.java        |  20 ++
 .../threads/impl/TxThreadContextProvider.java      |  15 ++
 .../threads/ManagedExecutorServiceTCCLTest.java    | 259 +++++++++++++++++++++
 .../threads/ManagedExecutorServiceTest.java        |   6 +-
 8 files changed, 417 insertions(+), 7 deletions(-)

diff --git a/container/openejb-core/src/main/java/org/apache/openejb/cdi/RequestScopedThreadContextListener.java b/container/openejb-core/src/main/java/org/apache/openejb/cdi/RequestScopedThreadContextListener.java
index c2df039e9e..aab55b1d95 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/cdi/RequestScopedThreadContextListener.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/cdi/RequestScopedThreadContextListener.java
@@ -20,23 +20,36 @@ package org.apache.openejb.cdi;
 import org.apache.openejb.BeanContext;
 import org.apache.openejb.core.ThreadContext;
 import org.apache.openejb.core.ThreadContextListener;
+import org.apache.openejb.util.LogCategory;
+import org.apache.openejb.util.Logger;
 import org.apache.webbeans.config.WebBeansContext;
 import org.apache.webbeans.spi.ContextsService;
 
 import jakarta.enterprise.context.RequestScoped;
 import jakarta.enterprise.context.spi.Context;
 
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
 /**
  * @version $Rev$ $Date$
  */
 public class RequestScopedThreadContextListener implements ThreadContextListener {
+
+    private static Logger LOG = Logger.getInstance(LogCategory.OPENEJB.createChild("ThreadContext"), "org.apache.openejb.cdi");
+
     @Override
     public void contextEntered(final ThreadContext oldContext, final ThreadContext newContext, boolean propagateTx) {
-
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ThreadContextListener contextEntered: oldContext=" + oldContext + ", newContext=" + newContext + ", from=" + fromStackTrace(new Exception()));
+        }
         final BeanContext beanContext = newContext.getBeanContext();
 
         final WebBeansContext webBeansContext = beanContext.getModuleContext().getAppContext().getWebBeansContext();
         if (webBeansContext == null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("ThreadContextListener contextEntered: webBeansContext is null");
+            }
             return;
         }
 
@@ -45,6 +58,9 @@ public class RequestScopedThreadContextListener implements ThreadContextListener
         final Context requestContext = CdiAppContextsService.class.cast(contextsService).getRequestContext(false);
 
         if (requestContext == null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("ThreadContextListener contextEntered: requestContext is null, creating new request scope");
+            }
             contextsService.startContext(RequestScoped.class, CdiAppContextsService.EJB_REQUEST_EVENT);
             newContext.set(DestroyContext.class, new DestroyContext(contextsService, newContext));
         }
@@ -52,16 +68,35 @@ public class RequestScopedThreadContextListener implements ThreadContextListener
 
     @Override
     public void contextExited(final ThreadContext exitedContext, final ThreadContext reenteredContext) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ThreadContextListener contextExited: exitedContext=" + exitedContext + ", reenteredContext=" + reenteredContext + ", from=" + fromStackTrace(new Exception()));
+        }
         if (exitedContext == null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("ThreadContextListener contextExited: exitedContext is null, not destroying RequestScope");
+            }
             return;
         }
 
         final DestroyContext destroyContext = exitedContext.get(DestroyContext.class);
 
-        if (destroyContext == null || destroyContext.threadContext != exitedContext) {
+        if (destroyContext == null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("ThreadContextListener contextExited: destroyContext is null, not destroying RequestScope");
+            }
             return;
         }
 
+        if (destroyContext.threadContext != exitedContext) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("ThreadContextListener contextExited: destroyContext does not match exited context, not destroying RequestScope");
+            }
+            return;
+        }
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ThreadContextListener contextExited: destroying RequestScope");
+        }
         destroyContext.contextsService.endContext(RequestScoped.class, CdiAppContextsService.EJB_REQUEST_EVENT);
         destroyContext.contextsService.removeThreadLocals();
     }
@@ -75,4 +110,13 @@ public class RequestScopedThreadContextListener implements ThreadContextListener
             this.threadContext = threadContext;
         }
     }
+
+    private static String fromStackTrace(final Throwable throwable) {
+        final StringWriter sw = new StringWriter();
+        final PrintWriter pw = new PrintWriter(sw);
+        throwable.printStackTrace(pw);
+        pw.flush();
+
+        return sw.toString();
+    }
 }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/core/ThreadContext.java b/container/openejb-core/src/main/java/org/apache/openejb/core/ThreadContext.java
index 0f2867a60f..ca9bf8fc4d 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/core/ThreadContext.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/core/ThreadContext.java
@@ -27,6 +27,7 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
 
 public class ThreadContext {
 
@@ -44,6 +45,12 @@ public class ThreadContext {
             throw new NullPointerException("newContext is null");
         }
 
+        if (newContext.entered.get()) {
+            throw new IllegalStateException("ThreadContext is already entered");
+        }
+
+        newContext.entered.set(true);
+
         // set the thread context class loader
         final Thread thread = Thread.currentThread();
         newContext.oldClassLoader = thread.getContextClassLoader();
@@ -77,6 +84,12 @@ public class ThreadContext {
             throw new IllegalStateException("No existing context");
         }
 
+        if (!exitingContext.entered.get()) {
+            throw new IllegalStateException("ThreadContext has not been entered, or has already been exited");
+        }
+
+        exitingContext.entered.set(false);
+
         // set the thread context class loader back
         Thread.currentThread().setContextClassLoader(exitingContext.oldClassLoader);
         exitingContext.oldClassLoader = null;
@@ -121,6 +134,7 @@ public class ThreadContext {
     private Operation currentOperation;
     private Class invokedInterface;
     private TransactionPolicy transactionPolicy;
+    private AtomicBoolean entered = new AtomicBoolean(false);
 
     /**
      * A boolean which keeps track of whether to discard the bean instance after the method invocation.
@@ -216,7 +230,8 @@ public class ThreadContext {
         return "ThreadContext{" +
             "beanContext=" + beanContext.getId() +
             ", primaryKey=" + primaryKey +
-            ", data=" + data.size() +
+            ", data(" + data.size() +
+            ")=" + dataToString(data) +
             ", oldClassLoader=" + oldClassLoader +
             ", currentOperation=" + currentOperation +
             ", invokedInterface=" + invokedInterface +
@@ -224,4 +239,11 @@ public class ThreadContext {
             ", discardInstance=" + discardInstance +
             '}';
     }
+
+    private String dataToString(final Map<Class, Object> data) {
+        return data.entrySet().stream()
+                .map(entry -> entry.getKey() + "=" + (entry.getValue() == null ? "null" : entry.getValue().hashCode()))
+                .collect(Collectors.joining(", "));
+
+    }
 }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ApplicationThreadContextProvider.java b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ApplicationThreadContextProvider.java
index 12d0333527..9a146976e9 100755
--- a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ApplicationThreadContextProvider.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ApplicationThreadContextProvider.java
@@ -73,9 +73,18 @@ public class ApplicationThreadContextProvider implements ThreadContextProvider,
 
             // Don't touch ThreadContext if it is already correct or none was captured
             boolean changeThreadContext = threadContext != null && threadContext != ThreadContext.getThreadContext();
-            ThreadContext oldThreadContext = changeThreadContext ? ThreadContext.enter(threadContext, false) : null;
+            ThreadContext oldThreadContext = changeThreadContext ? ThreadContext.enter(new ThreadContext(threadContext), false) : null;
             return new ApplicationThreadContextRestorer(oldCl, oldThreadContext, changeThreadContext);
         }
+
+        @Override
+        public String toString() {
+            return "ApplicationThreadContextSnapshot@" + System.identityHashCode(this) +
+                    "{appId=" + appId +
+                    "{threadContext=" + threadContext +
+                    '}';
+        }
+
     }
 
     public static class ApplicationThreadContextRestorer implements ThreadContextRestorer {
@@ -99,5 +108,15 @@ public class ApplicationThreadContextProvider implements ThreadContextProvider,
                 ThreadContext.exit(oldThreadContext);
             }
         }
+
+        @Override
+        public String toString() {
+            return "ApplicationThreadContextRestorer@" + System.identityHashCode(this) +
+                    "{oldClassLoader=" + oldClassLoader +
+                    "{oldThreadContext=" + oldThreadContext +
+                    "{exitThreadContext=" + exitThreadContext +
+                    '}';
+        }
+
     }
 }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ContextServiceImpl.java b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ContextServiceImpl.java
index 0f3777f18f..5f41c025e4 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ContextServiceImpl.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/ContextServiceImpl.java
@@ -27,9 +27,13 @@ import org.apache.openejb.OpenEJBRuntimeException;
 import org.apache.openejb.resource.thread.ManagedExecutorServiceImplFactory;
 import org.apache.openejb.threads.future.CUCompletableFuture;
 import org.apache.openejb.threads.task.CUTask;
+import org.apache.openejb.util.LogCategory;
+import org.apache.openejb.util.Logger;
 
 import javax.naming.NamingException;
+import java.io.PrintWriter;
 import java.io.Serializable;
+import java.io.StringWriter;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
@@ -54,6 +58,8 @@ public class ContextServiceImpl implements ContextService, Serializable {
     // TODO is lost after serialization, probably need to store some reference that can be resolved again after deserializing
     private transient ManagedExecutorService mes;
 
+    private static Logger LOG = Logger.getInstance(LogCategory.OPENEJB.createChild("ThreadContext"), "org.apache.openejb.cdi");
+
     public ContextServiceImpl(List<ThreadContextProvider> propagated, List<ThreadContextProvider> cleared, List<ThreadContextProvider> unchanged) {
         this.propagated = propagated;
         this.cleared = cleared;
@@ -188,6 +194,9 @@ public class ContextServiceImpl implements ContextService, Serializable {
             snapshots.add(snapshot);
         }
 
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ContextServiceImpl.snapshot snapshots=" + snapshots);
+        }
         return new Snapshot(snapshots);
     }
 
@@ -203,6 +212,10 @@ public class ContextServiceImpl implements ContextService, Serializable {
 
     public State enter(final Snapshot snapshot) {
 
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ContextServiceImpl.enter snapshot=" + snapshot);
+        }
+
         final List<ThreadContextRestorer> restorers = new ArrayList<>();
 
         for (ThreadContextSnapshot tcs : snapshot.snapshots()) {
@@ -213,10 +226,18 @@ public class ContextServiceImpl implements ContextService, Serializable {
             }
         }
 
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ContextServiceImpl.enter restorers=" + restorers);
+        }
+
         return new State(restorers);
     }
 
     public void exit(final State state) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("ContextServiceImpl.exit restorers=" + state.restorers());
+        }
+
         if (state != null) {
             final List<ThreadContextRestorer> restorers = state.restorers();
             for (ThreadContextRestorer restorer : restorers) {
@@ -308,4 +329,14 @@ public class ContextServiceImpl implements ContextService, Serializable {
     // a ClassLoader to restore which is not serializable
     public record State(List<ThreadContextRestorer> restorers) { }
     public record Snapshot(List<ThreadContextSnapshot> snapshots) implements Serializable { }
+
+    private static String fromStackTrace(final Throwable throwable) {
+        final StringWriter sw = new StringWriter();
+        final PrintWriter pw = new PrintWriter(sw);
+        throwable.printStackTrace(pw);
+        pw.flush();
+
+        return sw.toString();
+    }
+
 }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/SecurityThreadContextProvider.java b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/SecurityThreadContextProvider.java
index 7892fb7f1c..089ee31188 100755
--- a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/SecurityThreadContextProvider.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/SecurityThreadContextProvider.java
@@ -124,6 +124,16 @@ public class SecurityThreadContextProvider implements ThreadContextProvider, Ser
 
             return new SecurityThreadContextRestorer(associate, oldCtx, threadState);
         }
+
+        @Override
+        public String toString() {
+            return "SecurityThreadContextSnapshot@" + System.identityHashCode(this) +
+                    "{associate=" + associate +
+                    "{securityServiceState=" + securityServiceState +
+                    "{sc=" + sc +
+                    '}';
+        }
+
     }
 
     public static class SecurityThreadContextRestorer implements ThreadContextRestorer {
@@ -150,5 +160,15 @@ public class SecurityThreadContextProvider implements ThreadContextProvider, Ser
                 SECURITY_SERVICE.disassociate();
             }
         }
+
+        @Override
+        public String toString() {
+            return "SecurityThreadContextSnapshot@" + System.identityHashCode(this) +
+                    "{associate=" + associate +
+                    "{oldCtx=" + oldCtx +
+                    "{threadState=" + threadState +
+                    '}';
+        }
+
     }
 }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/TxThreadContextProvider.java b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/TxThreadContextProvider.java
index 09153c825c..8a413f2b66 100755
--- a/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/TxThreadContextProvider.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/threads/impl/TxThreadContextProvider.java
@@ -90,6 +90,13 @@ public class TxThreadContextProvider implements ThreadContextProvider, Serializa
                 throw new OpenEJBRuntimeException(e);
             }
         }
+
+        @Override
+        public String toString() {
+            return "TxThreadContextRestoringSnapshot@" + System.identityHashCode(this) +
+                    "{transaction=" + transaction +
+                    '}';
+        }
     }
 
     public static class TxThreadContextRestorer implements ThreadContextRestorer {
@@ -107,5 +114,13 @@ public class TxThreadContextProvider implements ThreadContextProvider, Serializa
                 throw new OpenEJBRuntimeException(e);
             }
         }
+
+        @Override
+        public String toString() {
+            return "TxThreadContextRestorer@" + System.identityHashCode(this) +
+                    "{transaction=" + transaction +
+                    '}';
+        }
+
     }
 }
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTCCLTest.java b/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTCCLTest.java
new file mode 100644
index 0000000000..c05dc53f09
--- /dev/null
+++ b/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTCCLTest.java
@@ -0,0 +1,259 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openejb.threads;
+
+import jakarta.annotation.Resource;
+import jakarta.ejb.EJB;
+import jakarta.ejb.Lock;
+import jakarta.ejb.LockType;
+import jakarta.ejb.Singleton;
+import jakarta.enterprise.concurrent.ManageableThread;
+import jakarta.enterprise.concurrent.ManagedExecutorService;
+import jakarta.enterprise.concurrent.ManagedThreadFactory;
+import org.apache.openejb.jee.EjbJar;
+import org.apache.openejb.jee.SingletonBean;
+import org.apache.openejb.junit.ApplicationComposer;
+import org.apache.openejb.testing.Configuration;
+import org.apache.openejb.testing.Module;
+import org.apache.openejb.testng.PropertiesBuilder;
+import org.apache.openejb.threads.impl.ContextServiceImpl;
+import org.apache.openejb.threads.impl.ContextServiceImplFactory;
+import org.apache.openejb.threads.impl.ManagedThreadFactoryImpl;
+import org.apache.openejb.threads.task.CURunnable;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.testng.Assert;
+
+import java.util.Properties;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@RunWith(ApplicationComposer.class)
+public class ManagedExecutorServiceTCCLTest {
+    @Configuration
+    public Properties configuration() {
+        return new PropertiesBuilder()
+                // don't set concurrent/es.context, it needs to resolve to the default ContextService in this case
+                .property("concurrent/es1", "new://Resource?type=ManagedExecutorService")
+                .property("concurrent/es1.core", "2")
+                .property("concurrent/es1.max", "10")
+                .property("concurrent/es1.keepAlive", "5 s")
+                .property("concurrent/es1.queue", "3")
+                .property("concurrent/es1.lazy", "True")
+                .property("concurrent/es1.threadFactory", "concurrent/tf")
+                .property("concurrent/es2", "new://Resource?type=ManagedExecutorService")
+                .property("concurrent/es2.core", "2")
+                .property("concurrent/es2.max", "10")
+                .property("concurrent/es2.keepAlive", "5 s")
+                .property("concurrent/es2.queue", "3")
+                .property("concurrent/es2.lazy", "True")
+                .property("concurrent/es2.threadFactory", "concurrent/tf")
+                .property("concurrent/tf", "new://Resource?type=ManagedThreadFactory&class-name=org.apache.openejb.threads.ManagedExecutorServiceTCCLTest$MyManagedThreadFactoryImplFactory&factory-name=create")
+                .property("concurrent/tf.prefix", "mes-test-thread-")
+                .property("concurrent/tf.priority", "5")
+                .property("concurrent/tf.context", "[automatic]")
+                .build();
+    }
+
+    @EJB
+    private ExecutorBean execBean;
+
+    @Module
+    public EjbJar bean() {
+        return new EjbJar()
+                .enterpriseBean(new SingletonBean(ExecutorBean.class).localBean())
+                .enterpriseBean(new SingletonBean(SecondExecutorBean.class).localBean())
+                .enterpriseBean(new SingletonBean(EchoBean.class).localBean());
+    }
+
+    @Test
+    public void test() throws Exception {
+        final String output = execBean.execute();
+        Assert.assertEquals("Hello TomEE!", output);
+    }
+
+    @Singleton
+    @Lock(LockType.READ)
+    public static class ExecutorBean {
+
+        @Resource(name = "concurrent/es1")
+        private ManagedExecutorService es1;
+
+        @EJB
+        private SecondExecutorBean secondBean;
+
+        public String execute() {
+            try {
+                final Future<String> future = es1.submit(() -> secondBean.run("TomEE!"));
+                return future.get(1, TimeUnit.SECONDS);
+            } catch (InterruptedException | ExecutionException | TimeoutException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+    }
+
+    @Singleton
+    @Lock(LockType.READ)
+    public static class SecondExecutorBean {
+
+        @Resource(name = "concurrent/es2")
+        private ManagedExecutorService es2;
+
+        @EJB
+        private EchoBean echoBean;
+
+        public String run(final String name) {
+            try {
+                final Future<String> future = es2.submit(() -> "Hello " + echoBean.echo(name));
+                return future.get(1, TimeUnit.SECONDS);
+            } catch (InterruptedException | ExecutionException | TimeoutException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    @Singleton
+    @Lock(LockType.READ)
+    public static class EchoBean {
+        public String echo(final String input) {
+            return input;
+        }
+    }
+
+    public static class MyManagedThreadFactoryImplFactory {
+        private String prefix = "openejb-managed-thread-";
+        private Integer priority;
+        private String context;
+
+        public ManagedThreadFactory create() {
+            return new MyManagedThreadFactoryImpl(prefix, priority, ContextServiceImplFactory.lookupOrDefault(context));
+        }
+
+        public void setPrefix(final String prefix) {
+            this.prefix = prefix;
+        }
+
+        public void setPriority(final int priority) {
+            this.priority = priority;
+        }
+
+        public void setContext(final String context) {
+            this.context = context;
+        }
+    }
+
+    /*
+     * This is a copy of ManagedThreadFactoryImpl, but with an override on the thread that prevents the
+     * context class loader being set to null - if a caller attempts to do this, the code
+     * throws an exception, which should cause the test to fail
+     */
+    public static class MyManagedThreadFactoryImpl implements ManagedThreadFactory  {
+        public static final String DEFAULT_PREFIX = "managed-thread-";
+        private static final AtomicInteger ID = new AtomicInteger();
+
+        private final ContextServiceImpl contextService;
+        private final String prefix;
+        private final Integer priority;
+
+        // Invoked by ThreadFactories.findThreadFactory via reflection
+        @SuppressWarnings("unused")
+        public MyManagedThreadFactoryImpl() {
+            this(DEFAULT_PREFIX, Thread.NORM_PRIORITY, ContextServiceImplFactory.getOrCreateDefaultSingleton());
+        }
+
+        public MyManagedThreadFactoryImpl(final String prefix, final Integer priority, final ContextServiceImpl contextService) {
+            this.prefix = prefix;
+            this.priority = priority;
+            this.contextService = contextService;
+        }
+
+        @Override
+        public Thread newThread(final Runnable r) {
+            final CURunnable wrapper = new CURunnable(r, contextService);
+            final Thread thread = new ManagedThread(wrapper);
+            thread.setDaemon(true);
+            thread.setName(prefix + ID.incrementAndGet());
+            thread.setContextClassLoader(ManagedThreadFactoryImpl.class.getClassLoader()); // ensure we use container loader as main context classloader to avoid leaks
+            if (priority != null) {
+                thread.setPriority(priority);
+            }
+            return thread;
+        }
+
+        @Override
+        public ForkJoinWorkerThread newThread(final ForkJoinPool pool) {
+            return new ManagedForkJoinWorkerThread(pool, priority, contextService);
+        }
+
+        public static class ManagedThread extends Thread implements ManageableThread {
+            public ManagedThread(final Runnable r) {
+                super(r);
+            }
+
+            @Override
+            public boolean isShutdown() {
+                return getState() == State.TERMINATED;
+            }
+
+            @Override
+            public void setContextClassLoader(ClassLoader cl) {
+                if (cl == null) {
+                    throw new IllegalArgumentException("The thread context class loader should not be set to null");
+                }
+                super.setContextClassLoader(cl);
+            }
+        }
+
+        public static class ManagedForkJoinWorkerThread extends ForkJoinWorkerThread {
+            private final ContextServiceImpl contextService;
+            private final Integer priority;
+
+            private final ContextServiceImpl.Snapshot snapshot;
+
+            private ContextServiceImpl.State state;
+            private Integer initialPriority;
+
+            protected ManagedForkJoinWorkerThread(final ForkJoinPool pool, final Integer priority, final ContextServiceImpl contextService) {
+                super(pool);
+                this.priority = priority;
+                this.contextService = contextService;
+
+                this.snapshot = contextService.snapshot(null);
+            }
+
+            @Override
+            protected void onStart() {
+                super.onStart();
+                initialPriority = getPriority();
+                if (priority != null) {
+                    setPriority(priority);
+                }
+
+                contextService.enter(snapshot);
+            }
+
+            @Override
+            protected void onTermination(Throwable exception) {
+                setPriority(initialPriority);
+                contextService.exit(state);
+
+                super.onTermination(exception);
+            }
+        }
+    }
+}
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTest.java b/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTest.java
index 36a3684106..06c4606899 100644
--- a/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTest.java
+++ b/container/openejb-core/src/test/java/org/apache/openejb/threads/ManagedExecutorServiceTest.java
@@ -142,9 +142,9 @@ public class ManagedExecutorServiceTest {
 
         @Override
         public Boolean call() throws Exception {
-/*            final RequestBean currentRequestBean =
- *            RequestBean.class.cast(bm.getReference(bm.resolve(bm.getBeans(RequestBean.class)),
- *            RequestBean.class, null));*/
+            /*            final RequestBean currentRequestBean =
+             *            RequestBean.class.cast(bm.getReference(bm.resolve(bm.getBeans(RequestBean.class)),
+             *            RequestBean.class, null));*/
             return /*CdiExecutorFacade.id == bean.getId()
                     && CdiExecutorFacade.id == currentRequestBean.getId()
                     && */CdiExecutorFacade.current.isValid();