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:groovy.ui.GroovyMain.java

private static void setupContextClassLoader(GroovyShell shell) {
    final Thread current = Thread.currentThread();
    class DoSetContext implements PrivilegedAction {
        ClassLoader classLoader;/*  w w w .j  a va2 s  .c  om*/

        public DoSetContext(ClassLoader loader) {
            classLoader = loader;
        }

        public Object run() {
            current.setContextClassLoader(classLoader);
            return null;
        }
    }

    AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}

From source file:com.huawei.streaming.cql.DriverContext.java

/**
 * classpathjar//w ww .  j a  v a 2s  . c om
 *
 * @param pathsToRemove jar
 * @throws IOException jar
 */
private 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()));

    if (pathsToRemove != null) {
        for (String onestr : pathsToRemove) {
            if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) {
                onestr = StringUtils.substring(onestr, CQLConst.I_7);
            }

            URL oneurl = (new File(onestr)).toURI().toURL();
            newPath.remove(oneurl);
        }
    }

    loader = new URLClassLoader(newPath.toArray(new URL[0]));
    curThread.setContextClassLoader(loader);
}

From source file:Main.java

ThreadDemo() {

    Thread t = new Thread(this);
    t.start();/*from   ww w .j av a2 s  .  c o  m*/
    ClassLoader c = t.getContextClassLoader();
    // sets the context ClassLoader for this Thread
    t.setContextClassLoader(c);
    System.out.println("Class = " + c.getClass());
    System.out.println("Parent = " + c.getParent());
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

private static void replaceTccl(ClassLoader leakedClassLoader, ClassLoader replacementClassLoader) {
    for (Thread thread : threads()) {
        if (thread != null) {
            ClassLoader cl = thread.getContextClassLoader();
            // do identity check to prevent expensive (and potentially dangerous) equals()
            if (leakedClassLoader == cl) {
                log.warn("Trying to patch leaked cl [" + leakedClassLoader + "] in thread [" + thread + "]");
                ThreadGroup tg = thread.getThreadGroup();
                // it's a JVM thread so use the System ClassLoader always
                boolean debug = log.isDebugEnabled();
                if (tg != null && JVM_THREAD_NAMES.contains(tg.getName())) {
                    thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
                    if (debug) {
                        log.debug("Replaced leaked cl in thread [" + thread + "] with system classloader");
                    }//from w w  w. jav  a2  s  . co  m
                } else {
                    thread.setContextClassLoader(replacementClassLoader);
                    if (debug) {
                        log.debug(
                                "Replaced leaked cl in thread [" + thread + "] with " + replacementClassLoader);
                    }
                }
            }
        }
    }
}

From source file:com.googlecode.arit.threads.ThreadScanner.java

public void clean(ClassLoader classLoader) {
    for (Thread thread : ThreadUtils.getAllThreads()) {
        if (thread.getContextClassLoader() == classLoader) {
            thread.setContextClassLoader(String.class.getClassLoader());
            LOG.info("Unset context class loader for thread " + thread.getName());
        }//from w  w w  . ja v a  2  s.  co  m
    }
}

From source file:org.apache.geronimo.axis.AxisDiscoveryCLWorkaroundGBean.java

public AxisDiscoveryCLWorkaroundGBean(ClassLoader classLoader) {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(classLoader);
    try {//from w w w. j  a  v  a2 s  .  c om
        //set up log
        DiscoverSingleton.find(org.apache.commons.logging.LogFactory.class, "commons-logging.properties", //org.apache.commons.logging.LogFactory.FACTORY_PROPERTIES,
                "org.apache.commons.logging.LogFactory");//org.apache.commons.logging.LogFactory.FACTORY_DEFAULT);

        //this sets the classloaders used in discovery. One is the current TCCL.
        AxisProperties.getNameDiscoverer();
    } finally {
        currentThread.setContextClassLoader(oldClassLoader);
    }
}

From source file:org.bonitasoft.engine.classloader.VirtualClassLoaderTest.java

/**
 * BS-7152 : test the loading of class when calling the JavaMethodInvoker
 * /*from   www .  j av a 2s .co  m*/
 * @throws Exception
 */
@Test
public void loadStudentInformation_toVirtualClassLoader_should_be_usable_via_JavaMethodInvoker()
        throws Exception {
    final VirtualClassLoader vcl = new VirtualClassLoader("org.bonitasoft", 1L,
            Thread.currentThread().getContextClassLoader());
    final Map<String, byte[]> resources = new HashMap<String, byte[]>(1);
    resources.put("UOSFaasApplication.jar",
            FileUtils.readFileToByteArray(new File("src/test/resources/UOSFaasApplication.jar")));
    final File tempDir = new File(System.getProperty("java.io.tmpdir"), "VirtualClassLoaderTest");
    final BonitaClassLoader bonitaClassLoader = new BonitaClassLoader(resources, "here", 154L, tempDir.toURI(),
            BonitaClassLoader.class.getClassLoader());

    vcl.setClassLoader(bonitaClassLoader);
    final Object objectToInvokeJavaMethodOn = vcl
            .loadClass("au.edu.sydney.faas.applicationstudent.StudentRequest").getConstructors()[0]
                    .newInstance();
    final Object valueToSetObjectWith = vcl
            .loadClass("au.edu.sydney.faas.applicationstudent.StudentInformation").getConstructors()[0]
                    .newInstance();

    ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setContextClassLoader(vcl);
            return t;
        }
    });

    Future<Object> jmiFuture = executor.submit(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try {
                JavaMethodInvoker jmi = new JavaMethodInvoker();
                jmi.invokeJavaMethod("au.edu.sydney.faas.applicationstudent.StudentInformation",
                        valueToSetObjectWith, objectToInvokeJavaMethodOn, "setStudentInformation",
                        "au.edu.sydney.faas.applicationstudent.StudentInformation");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    jmiFuture.get();

    // To clean
    bonitaClassLoader.destroy();
}

From source file:org.hyperic.hq.bizapp.server.session.HQInternalService.java

private void runInContext(Runnable runner, ClassLoader cl) {
    Thread thread = new Thread(runner);
    thread.setContextClassLoader(cl);
    thread.start();//from w  w w.  j  a  v  a  2 s . c  o m
    try {
        // 5 min timeout - should not take more than 5 mins to grab a value
        final StopWatch watch = new StopWatch();
        final long timeout = 5 * 60 * 1000;
        thread.join(timeout);
        if (watch.getElapsed() >= timeout) {
            log.warn("timeout when running job in a class loader context.  This could mean that the db is hung "
                    + watch);
        }
    } catch (InterruptedException e) {
        log.error(e, e);
    }
}

From source file:org.intalio.tempo.workflow.ServiceObjectSupplier.java

public Object getServiceObject(AxisService service) throws AxisFault {
    Parameter fac = service.getParameter("SpringBeanFactory");
    if (fac != null) {
        Thread thread = Thread.currentThread();
        ClassLoader oldClassLoader = thread.getContextClassLoader();
        try {//  w  w  w . j  ava  2 s. c  o m
            thread.setContextClassLoader(SpringInit.CONTEXT.getClass().getClassLoader());
            String factoryName = (String) fac.getValue();
            LOG.info("Using factory:" + factoryName);
            Object o = SpringInit.CONTEXT.getBean(factoryName);
            //LOG.info("Class:"+o.getClass().getName());
            FactoryBean factory = (FactoryBean) o;
            return factory.getObject();
        } catch (Exception e) {
            LOG.info("Error while using factory", e);
        } finally {
            thread.setContextClassLoader(oldClassLoader);
        }
    }

    String beanName = "#unspecified#";
    Parameter p = service.getParameter("SpringBeanName");
    if (p != null) {
        beanName = (String) p.getValue();
    }
    Object bean = SpringInit.CONTEXT.getBean(beanName);
    if (bean == null) {
        LOG.error("Bean not found: " + beanName);
    }
    return bean;
}

From source file:org.apache.phoenix.log.QueryLoggerDisruptor.java

public QueryLoggerDisruptor(Configuration configuration) throws SQLException {
    WaitStrategy waitStrategy;/*from  w  w  w  . java  2  s  . c o m*/
    try {
        waitStrategy = (WaitStrategy) Class
                .forName(configuration.get(QueryServices.LOG_BUFFER_WAIT_STRATEGY, DEFAULT_WAIT_STRATEGY))
                .newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new SQLException(e);
    }

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("QueryLogger" + "-thread-%s")
            .setDaemon(true).setThreadFactory(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    final Thread result = Executors.defaultThreadFactory().newThread(r);
                    result.setContextClassLoader(QueryLoggerDisruptor.class.getClass().getClassLoader());
                    return result;
                }
            }).build();
    disruptor = new Disruptor<RingBufferEvent>(RingBufferEvent.FACTORY,
            configuration.getInt(QueryServices.LOG_BUFFER_SIZE, RING_BUFFER_SIZE), threadFactory,
            ProducerType.MULTI, waitStrategy);
    final ExceptionHandler<RingBufferEvent> errorHandler = new QueryLoggerDefaultExceptionHandler();
    disruptor.setDefaultExceptionHandler(errorHandler);

    final QueryLogDetailsEventHandler[] handlers = { new QueryLogDetailsEventHandler(configuration) };
    disruptor.handleEventsWith(handlers);
    LOG.info("Starting  QueryLoggerDisruptor for with ringbufferSize="
            + disruptor.getRingBuffer().getBufferSize() + ", waitStrategy="
            + waitStrategy.getClass().getSimpleName() + ", " + "exceptionHandler=" + errorHandler + "...");
    disruptor.start();

}