Example usage for java.lang Thread setContextClassLoader

List of usage examples for java.lang Thread setContextClassLoader

Introduction

In this page you can find the example usage for java.lang Thread setContextClassLoader.

Prototype

public void setContextClassLoader(ClassLoader cl) 

Source Link

Document

Sets the context ClassLoader for this Thread.

Usage

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
 *///from  w w w  .  j a  va 2 s  .c  o m
@SuppressWarnings("deprecation")
protected void stopThreads() {
    final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
    final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
    final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE

    for (Thread thread : getAllThreads()) {
        @SuppressWarnings("RedundantCast")
        final Runnable runnable = (oracleTarget != null) ? (Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE  
                (Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE

        if (thread != Thread.currentThread() && // Ignore current thread
                (isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {

            if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
                // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
                // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
                if (stopThreads) {
                    info("Found JURT thread " + thread.getName() + "; starting "
                            + JURTKiller.class.getSimpleName());
                    new JURTKiller(thread).start();
                } else
                    warn("JURT thread " + thread.getName() + " is still running in web app");
            } else if (thread.getThreadGroup() != null && ("system".equals(thread.getThreadGroup().getName()) || // System thread
                    "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)

                if ("Keep-Alive-Timer".equals(thread.getName())) {
                    thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
                    debug("Changed contextClassLoader of HTTP keep alive thread");
                }
            } else if (thread.isAlive()) { // Non-system, running in web app

                if ("java.util.TimerThread".equals(thread.getClass().getName())) {
                    if (stopTimerThreads) {
                        warn("Stopping Timer thread running in classloader.");
                        stopTimerThread(thread);
                    } else {
                        info("Timer thread is running in classloader, but will not be stopped");
                    }
                } else {
                    // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
                    if (workerClass != null && workerClass.isInstance(runnable)) {
                        if (stopThreads) {
                            warn("Shutting down " + ThreadPoolExecutor.class.getName()
                                    + " running within the classloader.");
                            try {
                                // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
                                final Field workerExecutor = findField(workerClass, "this$0");
                                final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
                                executor.shutdownNow();
                            } catch (Exception ex) {
                                error(ex);
                            }
                        } else
                            info(ThreadPoolExecutor.class.getName()
                                    + " running within the classloader will not be shut down.");
                    }

                    final String displayString = "'" + thread + "' of type " + thread.getClass().getName();

                    if (stopThreads) {
                        final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
                        warn("Stopping Thread " + displayString + " running in web app " + waitString);

                        if (threadWaitMs > 0) {
                            try {
                                thread.join(threadWaitMs); // Wait for thread to run
                            } catch (InterruptedException e) {
                                // Do nothing
                            }
                        }

                        // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
                        // In this case however, the alternative is a classloader leak, which may or may not be considered worse.
                        if (thread.isAlive())
                            thread.stop();
                    } else {
                        warn("Thread " + displayString + " is still running in web app");
                    }

                }
            }
        }
    }
}

From source file:plugins.tprovoost.Microscopy.MicroManagerForIcy.MMMainFrame.java

@Override
public IAcquisitionEngine2010 getAcquisitionEngine2010() {
    IAcquisitionEngine2010 pipeline = null;
    try {/*ww  w  .j a va2  s  .co m*/
        Thread currentThread = Thread.currentThread();
        ClassLoader currentClassLoader = currentThread.getContextClassLoader();
        currentThread.setContextClassLoader(PluginLoader.getLoader());
        Class<?> acquisitionEngine2010Class = ClassUtil.findClass("org.micromanager.AcquisitionEngine2010");
        if (acquisitionEngine2010Class != null) {
            pipeline = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructors()[0]
                    .newInstance(this);
        }
        currentThread.setContextClassLoader(currentClassLoader);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoClassDefFoundError e) {
        e.printStackTrace();
    }
    return pipeline;
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

/**
 * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
 *///  w  ww  .  j ava 2s  .  c  o  m
@SuppressWarnings("deprecation")
protected void stopThreads() {
    final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
    final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
    final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE

    for (Thread thread : getAllThreads()) {
        final Runnable runnable = (oracleTarget != null) ? (Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE  
                (Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE

        if (thread != Thread.currentThread() && // Ignore current thread
                (isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {

            if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
                // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
                // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
                if (stopThreads) {
                    info("Found JURT thread " + thread.getName() + "; starting "
                            + JURTKiller.class.getSimpleName());
                    new JURTKiller(thread).start();
                } else
                    warn("JURT thread " + thread.getName() + " is still running in web app");
            } else if (thread.getThreadGroup() != null && ("system".equals(thread.getThreadGroup().getName()) || // System thread
                    "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)

                if ("Keep-Alive-Timer".equals(thread.getName())) {
                    thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
                    debug("Changed contextClassLoader of HTTP keep alive thread");
                }
            } else if (thread.isAlive()) { // Non-system, running in web app

                if ("java.util.TimerThread".equals(thread.getClass().getName())) {
                    if (stopTimerThreads) {
                        warn("Stopping Timer thread running in classloader.");
                        stopTimerThread(thread);
                    } else {
                        info("Timer thread is running in classloader, but will not be stopped");
                    }
                } else {
                    // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
                    if (workerClass != null && workerClass.isInstance(runnable)) {
                        if (stopThreads) {
                            warn("Shutting down " + ThreadPoolExecutor.class.getName()
                                    + " running within the classloader.");
                            try {
                                // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
                                final Field workerExecutor = findField(workerClass, "this$0");
                                final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
                                executor.shutdownNow();
                            } catch (Exception ex) {
                                error(ex);
                            }
                        } else
                            info(ThreadPoolExecutor.class.getName()
                                    + " running within the classloader will not be shut down.");
                    }

                    final String displayString = "'" + thread + "' of type " + thread.getClass().getName();

                    if (stopThreads) {
                        final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
                        warn("Stopping Thread " + displayString + " running in web app " + waitString);

                        if (threadWaitMs > 0) {
                            try {
                                thread.join(threadWaitMs); // Wait for thread to run
                            } catch (InterruptedException e) {
                                // Do nothing
                            }
                        }

                        // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
                        // In this case however, the alternative is a classloader leak, which may or may not be considered worse.
                        if (thread.isAlive())
                            thread.stop();
                    } else {
                        warn("Thread " + displayString + " is still running in web app");
                    }

                }
            }
        }
    }
}

From source file:org.apache.hadoop.hive.ql.exec.Utilities.java

/**
 * remove elements from the classpath.//from   w  ww .j  a va2 s.  c  om
 *
 * @param pathsToRemove
 *          Array of classpath elements
 */
public static void removeFromClassPath(String[] pathsToRemove) throws IOException {
    Thread curThread = Thread.currentThread();
    URLClassLoader loader = (URLClassLoader) curThread.getContextClassLoader();
    Set<URL> newPath = new HashSet<URL>(Arrays.asList(loader.getURLs()));

    for (String onestr : pathsToRemove) {
        URL oneurl = urlFromPathString(onestr);
        if (oneurl != null) {
            newPath.remove(oneurl);
        }
    }
    JavaUtils.closeClassLoader(loader);
    // This loader is closed, remove it from cached registry loaders to avoid removing it again.
    Registry reg = SessionState.getRegistry();
    if (reg != null) {
        reg.removeFromUDFLoaders(loader);
    }

    loader = new UDFClassLoader(newPath.toArray(new URL[0]));
    curThread.setContextClassLoader(loader);
    SessionState.get().getConf().setClassLoader(loader);
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl.java

protected OrigContextClassLoader setContextClassLoader(ExecutionContext context, Map unitResources,
        boolean inMemoryUnit, RepositoryContextHandle repositoryContextHandle) {
    Thread thread = Thread.currentThread();
    ClassLoader origClassLoader = thread.getContextClassLoader();
    ClassLoader jarsClassLoader;//from  www  .jav a2  s . c o m
    ClassLoader newClassLoader = null;

    List jarFiles = getJarFiles(context, unitResources, !inMemoryUnit);
    if (jarFiles.isEmpty()) {
        jarsClassLoader = origClassLoader;
    } else {
        newClassLoader = jarsClassLoader = getJarsClassLoader(origClassLoader, jarFiles);
    }

    RepositoryContext repositoryContext = repositoryContextHandle == null ? null
            : repositoryContextHandle.getRepositoryContext();
    if (repositoryContext != null || RepositoryUtil.hasThreadRepositoryContext()) {
        //use the repository context for the keys? not required for now as for now the context is always freshly set on the thread.
        Map resourceBundleKeys = getResourceBundleKeys(context, unitResources);
        if (!resourceBundleKeys.isEmpty()) {
            newClassLoader = getResourcesClassLoader(jarsClassLoader, resourceBundleKeys, inMemoryUnit,
                    repositoryContext);
        }
    }

    OrigContextClassLoader origContext;
    if (newClassLoader == null) {
        origContext = OrigContextClassLoader.NOT_SET;
    } else {
        origContext = new OrigContextClassLoader(origClassLoader, jarFiles);
        thread.setContextClassLoader(newClassLoader);
    }

    return origContext;
}