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:br.com.uol.runas.classloader.ClassLoaderGC.java

private void releaseFromThreads(WeakReference<ClassLoader> classLoader) {
    final List<Thread> threads = new ArrayList<Thread>(Thread.getAllStackTraces().keySet());

    for (Thread thread : threads) {
        if (Objects.equals(classLoader.get(), thread.getContextClassLoader())) {
            thread.setContextClassLoader(null);
        }//from   ww  w  .j  av  a2 s.  c  om
    }
}

From source file:org.apache.hadoop.hbase.coprocessor.BaseEnvironment.java

/** Clean up the environment */
@Override//from  w ww  .  java2s.  c o  m
public void shutdown() {
    if (state == Coprocessor.State.ACTIVE) {
        state = Coprocessor.State.STOPPING;
        Thread currentThread = Thread.currentThread();
        ClassLoader hostClassLoader = currentThread.getContextClassLoader();
        try {
            currentThread.setContextClassLoader(this.getClassLoader());
            impl.stop(this);
            state = Coprocessor.State.STOPPED;
        } catch (IOException ioe) {
            LOG.error("Error stopping coprocessor " + impl.getClass().getName(), ioe);
        } finally {
            currentThread.setContextClassLoader(hostClassLoader);
        }
    } else {
        LOG.warn("Not stopping coprocessor " + impl.getClass().getName() + " because not active (state="
                + state.toString() + ")");
    }
    synchronized (openTables) {
        // clean up any table references
        for (Table table : openTables) {
            try {
                ((HTableWrapper) table).internalClose();
            } catch (IOException e) {
                // nothing can be done here
                LOG.warn("Failed to close " + table.getName(), e);
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.management.probes.ProbeManagerImpl.java

protected void doRunProbe(ProbeInfo probe) {
    if (!probe.isEnabled()) {
        return;/*from  www.  j  a v  a2  s . c o  m*/
    }
    try {
        ProbeInfoImpl probeInfoImpl = (ProbeInfoImpl) probe;
        Thread currentThread = Thread.currentThread();
        ClassLoader lastLoader = currentThread.getContextClassLoader();
        currentThread.setContextClassLoader(ProbeInfoImpl.class.getClassLoader());
        probeInfoImpl.lastRunnedDate = new Date();
        probeInfoImpl.runnedCount += 1;
        try {
            Probe runnableProbe = probesByShortcuts.get(probe.getShortcutName());
            probeInfoImpl.lastStatus = runnableProbe.run();
            if (probeInfoImpl.lastStatus.isSuccess()) {
                probeInfoImpl.lastSucceedDate = probeInfoImpl.lastRunnedDate;
                probeInfoImpl.lastSuccessStatus = probeInfoImpl.lastStatus;
                probeInfoImpl.successCount += 1;
            } else {
                probeInfoImpl.lastFailureStatus = probeInfoImpl.lastStatus;
                probeInfoImpl.failureCount += 1;
                probeInfoImpl.lastFailureDate = probeInfoImpl.lastRunnedDate;
            }
        } catch (Throwable e) {
            probeInfoImpl.failureCount += 1;
            probeInfoImpl.lastFailureDate = new Date();
            probeInfoImpl.lastFailureStatus = ProbeStatus.newError(e);
        } finally {
            probeInfoImpl.lastDuration = doGetDuration(probeInfoImpl.lastRunnedDate, new Date());
            currentThread.setContextClassLoader(lastLoader);
        }

        if (probe.isInError()) {
            succeed.remove(probe);
            failed.add(probe);
        } else {
            failed.remove(probe);
            succeed.add(probe);
        }
    } catch (Throwable e) {
        succeed.remove(probe);
        failed.add(probe);
    }
}

From source file:org.apache.openejb.server.axis.assembler.CommonsSchemaLoader.java

private Definition readWsdl(URI wsdlURI) throws OpenEJBException {
    Definition definition;//from   w w  w.j  ava2 s  .  c  o  m
    WSDLFactory wsdlFactory;
    try {
        wsdlFactory = WSDLFactory.newInstance();
    } catch (WSDLException e) {
        throw new OpenEJBException("Could not create WSDLFactory", e);
    }
    WSDLReader wsdlReaderNoImport = wsdlFactory.newWSDLReader();
    wsdlReaderNoImport.setFeature("javax.wsdl.importDocuments", false);
    ExtensionRegistry extensionRegistry = new PopulatedExtensionRegistry();
    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            extensionRegistry.getDefaultSerializer());

    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            extensionRegistry.getDefaultSerializer());

    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            extensionRegistry.getDefaultSerializer());
    wsdlReaderNoImport.setExtensionRegistry(extensionRegistry);

    JarWSDLLocator wsdlLocator = new JarWSDLLocator(wsdlURI);
    WSDLReader wsdlReader = wsdlFactory.newWSDLReader();

    Thread thread = Thread.currentThread();
    ClassLoader oldCl = thread.getContextClassLoader();
    thread.setContextClassLoader(this.getClass().getClassLoader());
    try {
        try {
            definition = wsdlReader.readWSDL(wsdlLocator);
        } catch (WSDLException e) {
            throw new OpenEJBException("Failed to read wsdl document", e);
        } catch (RuntimeException e) {
            throw new OpenEJBException(e.getMessage(), e);
        }
    } finally {
        thread.setContextClassLoader(oldCl);
    }

    return definition;
}

From source file:org.springframework.osgi.web.tomcat.internal.Activator.java

public void stop(BundleContext context) throws Exception {
    // unpublish service first
    registration.unregister();/*from  www.j  a v  a  2s  .c  o m*/
    urlRegistration.unregister();

    log.info("Unpublished  " + ServerInfo.getServerInfo() + " OSGi service");

    // default startup procedure
    ClassLoader cl = Activator.class.getClassLoader();
    Thread current = Thread.currentThread();
    ClassLoader old = current.getContextClassLoader();

    try {
        current.setContextClassLoader(cl);
        //reset CCL 
        // current.setContextClassLoader(null);
        log.info("Stopping " + ServerInfo.getServerInfo() + " ...");
        server.stop();
        log.info("Succesfully stopped " + ServerInfo.getServerInfo());
    } catch (Exception ex) {
        log.error("Cannot stop " + ServerInfo.getServerInfo(), ex);
        throw ex;
    } finally {
        current.setContextClassLoader(old);
    }
}

From source file:com.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public synchronized void start() {
    checkExecCompleteState();//w w  w. j a v a2s.  com
    checkExecCancelledState();
    checkExecRunningState();

    callOperatorOpen();

    final AtomicInteger countdown = new AtomicInteger(sourceRunnables.size());
    threads = new ArrayList<Thread>();
    for (int i = 0; i < sourceRunnables.size(); i++) {
        GraphSourceRunnable runnable = sourceRunnables.get(i);
        String threadName = "esper." + dataFlowName + "-" + i;
        Thread thread = new Thread(runnable, threadName);
        thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
        thread.setDaemon(true);
        runnable.addCompletionListener(new CompletionListener() {
            public void completed() {
                int remaining = countdown.decrementAndGet();
                if (remaining == 0) {
                    EPDataFlowInstanceImpl.this.completed();
                }
            }
        });
        threads.add(thread);
        thread.start();
    }
    setState(EPDataFlowState.RUNNING);
}

From source file:org.yestech.maven.HibernateSearchBuildIndexesMojo.java

public void execute() throws MojoExecutionException {

    if (skip) {//w  w w  . j av a2  s .  com
        getLog().info("Skipping search index population");
        return;
    }

    Thread thread = Thread.currentThread();
    ClassLoader oldClassLoader = thread.getContextClassLoader();
    thread.setContextClassLoader(getClassLoader());

    FullTextSession fullTextSession = null;
    Connection con = null;
    try {

        Class.forName(driver);
        con = java.sql.DriverManager.getConnection(url, username, password);

        Configuration configuration = new AnnotationConfiguration();
        configuration = configuration.configure(config);
        if (StringUtils.isNotBlank(dialect)) {
            configuration.setProperty("hibernate.dialect", dialect);
        }

        prepareIndexDir(configuration);

        if (StringUtils.isNotBlank(directoryProvider)) {
            configuration.setProperty("hibernate.search.default.directory_provider", directoryProvider);
        }

        fullTextSession = processObjects(fullTextSession, con, configuration);
    } catch (Exception e) {
        throw new MojoExecutionException("Build " + e.getMessage(), e);
    } finally {
        if (fullTextSession != null) {
            fullTextSession.flushToIndexes();
            fullTextSession.flush();
            fullTextSession.close();
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                getLog().error(e);
            }
        }
        thread.setContextClassLoader(oldClassLoader);
    }

}

From source file:disko.flow.analyzers.FullRelexAnalyzer.java

/**
 * Initialize the pool of LinkParserClients, creating CLIENT_POOL_SIZE
 * instances, which connects to ports FIRST_PORT, FIRST_PORT+1, ...,
 * FIRST_PORT+(CLIENT_POOL_SIZE-1)//from  www . j a  v  a2 s  . c  om
 */
private void initializePool() throws InterruptedException {
    sentenceAlgorithmApplier = new SentenceAlgorithmApplier();
    // phraseMarkup = new PhraseMarkup();
    if (morphy == null)
        morphy = MorphyFactory.getImplementation();

    if ((hosts == null) || (hosts.size() == 0)) {
        for (int i = 0; i < DEFAULT_CLIENT_COUNT; i++) {
            addHost(DEFAULT_HOST, DEFAULT_FIRST_PORT + i);
        }
    }

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    // +1 submission thread
    exec = Executors.newFixedThreadPool(hosts.size() + 1, new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setContextClassLoader(loader);
            t.setDaemon(true);
            return t;
        }
    });
    pool = new ArrayBlockingQueue<RelexContext>(hosts.size() + inProcessParsers);

    for (HostPort hp : hosts) {
        RemoteLGParser parser = new RemoteLGParser();
        parser.getLinkGrammarClient().setHostname(hp.host);
        parser.getLinkGrammarClient().setPort(hp.port);
        configureParser(parser);
        RelexContext context = new RelexContext(parser, morphy);
        pool.put(context);
    }

    for (int i = hosts.size(); i < pool.size(); i++) {
        LocalLGParser parser = new LocalLGParser();
        configureParser(parser);
        RelexContext context = new RelexContext(parser, morphy);
        pool.put(context);
    }
}

From source file:org.apache.hadoop.mapreduce.v2.app.commit.CommitterEventHandler.java

@Override
protected void serviceStart() throws Exception {
    ThreadFactoryBuilder tfBuilder = new ThreadFactoryBuilder().setNameFormat("CommitterEvent Processor #%d");
    if (jobClassLoader != null) {
        // if the job classloader is enabled, we need to use the job classloader
        // as the thread context classloader (TCCL) of these threads in case the
        // committer needs to load another class via TCCL
        ThreadFactory backingTf = new ThreadFactory() {
            @Override/*w w  w. ja va  2 s  .co  m*/
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setContextClassLoader(jobClassLoader);
                return thread;
            }
        };
        tfBuilder.setThreadFactory(backingTf);
    }
    ThreadFactory tf = tfBuilder.build();
    launcherPool = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf);
    eventHandlingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            CommitterEvent event = null;
            while (!stopped.get() && !Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    if (!stopped.get()) {
                        LOG.error("Returning, interrupted : " + e);
                    }
                    return;
                }
                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(new EventProcessor(event));
            }
        }
    });
    eventHandlingThread.setName("CommitterEvent Handler");
    eventHandlingThread.start();
    super.serviceStart();
}

From source file:org.springframework.osgi.web.tomcat.internal.Activator.java

public void start(BundleContext context) throws Exception {
    this.bundleContext = context;
    // do the initialization on a different thread
    // so the activator finishes fast
    startupThread = new Thread(new Runnable() {

        public void run() {
            log.info("Starting " + ServerInfo.getServerInfo() + " ...");

            // default startup procedure
            ClassLoader cl = Activator.class.getClassLoader();
            Thread current = Thread.currentThread();
            ClassLoader old = current.getContextClassLoader();

            try {
                current.setContextClassLoader(cl);

                server = createCatalinaServer(bundleContext.getBundle());

                server.start();/* w  ww.  jav  a  2s.c  o  m*/

                Connector[] connectors = server.findConnectors();
                for (int i = 0; i < connectors.length; i++) {
                    Connector conn = connectors[i];
                    log.info("Succesfully started " + ServerInfo.getServerInfo() + " @ " + conn.getDomain()
                            + ":" + conn.getPort());
                }

                // register URL service
                urlRegistration = registerTomcatJNDIUrlService();
                // publish server as an OSGi service
                registration = publishServerAsAService(server);
                log.info("Published " + ServerInfo.getServerInfo() + " as an OSGi service");
            } catch (Exception ex) {
                String msg = "Cannot start " + ServerInfo.getServerInfo();
                log.error(msg, ex);
                throw new RuntimeException(msg, ex);
            } finally {
                current.setContextClassLoader(old);
            }
        }
    }, "Tomcat Catalina Start Thread");

    startupThread.start();
}