List of usage examples for java.lang Thread getContextClassLoader
@CallerSensitive
public ClassLoader getContextClassLoader()
From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java
@SuppressWarnings("deprecation") private static void clearReferencesThreads(ClassLoader classLoader) { Thread[] threads = getThreads(); // Iterate over the set of threads for (Thread thread : threads) { if (thread != null) { ClassLoader ccl = thread.getContextClassLoader(); if (ccl != null && ccl == classLoader) { // Don't warn about this thread if (thread == Thread.currentThread()) { continue; }//from w w w .j a v a2s .co m // Skip threads that have already died if (!thread.isAlive()) { continue; } // Don't warn about JVM controlled threads ThreadGroup tg = thread.getThreadGroup(); if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) { continue; } // TimerThread is not normally visible if (thread.getClass().getName().equals("java.util.TimerThread")) { clearReferencesStopTimerThread(thread); continue; } if (logger.isLoggable(Level.FINE)) logger.fine("A thread named [" + thread.getName() + "] started but has failed to stop it. This is very likely to create a memory leak."); // Don't try an stop the threads unless explicitly // configured to do so if (!clearReferencesStopThreads) { continue; } // If the thread has been started via an executor, try // shutting down the executor try { Field targetField = thread.getClass().getDeclaredField("target"); targetField.setAccessible(true); Object target = targetField.get(thread); if (target != null && target.getClass().getCanonicalName() .equals("java.util.concurrent.ThreadPoolExecutor.Worker")) { Field executorField = target.getClass().getDeclaredField("this$0"); executorField.setAccessible(true); Object executor = executorField.get(target); if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).shutdownNow(); } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to terminate thread named [" + thread.getName() + "]", e); } // This method is deprecated and for good reason. This is // very risky code but is the only option at this point. // A *very* good reason for apps to do this clean-up // themselves. thread.stop(); } } } }
From source file:be.fedict.eid.tsl.BelgianTrustServiceListFactory.java
private static X509Certificate loadCertificateFromResource(String resourceName) { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName); if (null == certificateInputStream) { throw new IllegalArgumentException("could not load certificate resource: " + resourceName); }/*from w w w .j a v a2 s. c om*/ try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(certificateInputStream); return certificate; } catch (CertificateException e) { throw new RuntimeException("certificate factory error: " + e.getMessage(), e); } }
From source file:be.fedict.eid.tsl.BelgianTrustServiceListFactory.java
private static Document loadDocumentFromResource(String resourceName) { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); InputStream documentInputStream = classLoader.getResourceAsStream(resourceName); if (null == documentInputStream) { throw new IllegalArgumentException("resource not found: " + resourceName); }//from w w w . j av a2 s .c om DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document tslDocument = documentBuilder.parse(documentInputStream); return tslDocument; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java
private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName) throws HibernateException { //ClassLoader cl1; if (sessionFactory == null) { if (jndiName == null || jndiName.trim().length() == 0) jndiName = CommonConstant.DEFAULT_JNDI_URL; Context initCtx = null;//from w w w .j a v a 2s.co m try { initCtx = new InitialContext(); sessionFactory = (SessionFactory) initCtx.lookup(jndiName); return; } catch (Exception e) { logger.log(Level.INFO, "Unable to get JNDI data source connection", e); } finally { if (initCtx != null) try { initCtx.close(); } catch (NamingException e) { //ignore } } Thread thread = Thread.currentThread(); try { //Class.forName("org.hibernate.Configuration"); //Configuration ffff = new Configuration(); //Class.forName("org.apache.commons.logging.LogFactory"); oldloader = thread.getContextClassLoader(); //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration"); //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory"); //refreshURLs(); //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader()); ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader); //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0])); thread.setContextClassLoader(testLoader); //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration"); //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader); //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader); //Configuration cfg=null; //cfg = new Configuration(); //Object oo = cls.newInstance(); //Configuration cfg = (Configuration)oo; Configuration cfg = new Configuration(); buildConfig(hibfile, mapdir, cfg); Class<? extends Driver> driverClass = testLoader .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class); Driver driver = driverClass.newInstance(); WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class")); boolean foundDriver = false; Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver nextDriver = (Driver) drivers.nextElement(); if (nextDriver.getClass() == wd.getClass()) { if (nextDriver.toString().equals(wd.toString())) { foundDriver = true; break; } } } if (!foundDriver) { DriverManager.registerDriver(wd); } sessionFactory = cfg.buildSessionFactory(); //configuration = cfg; HibernateMapDirectory = mapdir; HibernateConfigFile = hibfile; } catch (Throwable e) { e.printStackTrace(); throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e); } finally { thread.setContextClassLoader(oldloader); } } }
From source file:org.openmrs.util.OpenmrsClassLoader.java
/** * Sets the class loader, for all threads referencing a destroyed openmrs class loader, * to the current one./*from w ww .ja v a2s . c o m*/ */ public static void setThreadsToNewClassLoader() { //Give ownership of all threads loaded by the old class loader to the new one. //Examples of such threads are: Keep-Alive-Timer, MySQL Statement Cancellation Timer, etc //That way they will no longer hold onto the destroyed OpenmrsClassLoader and hence //allow it to be garbage collected after a spring application context refresh, when a new one is created. Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread thread : threadArray) { ClassLoader classLoader = thread.getContextClassLoader(); //Some threads have a null class loader reference. e.g Finalizer, Reference Handler, etc if (classLoader == null) { continue; } //Threads referencing the current class loader are good. if (classLoader == getInstance()) { continue; } //For threads referencing any destroyed class loader, point them to the new one. if (classLoader instanceof OpenmrsClassLoader) { thread.setContextClassLoader(getInstance()); } } }
From source file:org.openmrs.util.OpenmrsClassLoader.java
public static void onShutdown() { //Since we are shutting down, stop all threads that reference the openmrs class loader. Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread thread : threadArray) { ClassLoader classLoader = thread.getContextClassLoader(); //Threads like Finalizer, Reference Handler, etc have null class loader reference. if (classLoader == null) { continue; }/* w w w. j a v a2 s. co m*/ if (classLoader instanceof OpenmrsClassLoader) { try { //Set to WebappClassLoader just in case stopping fails. thread.setContextClassLoader(classLoader.getParent()); //Stopping the current thread will halt all current cleanup. //So do not ever ever even attempt stopping it. :) if (thread == Thread.currentThread()) { continue; } log.info("onShutdown Stopping thread: " + thread.getName()); thread.stop(); } catch (Exception ex) { log.error(ex.getMessage(), ex); } } } clearReferences(); }
From source file:org.openmrs.util.OpenmrsClassLoader.java
private static List<Thread> listThreads(ThreadGroup group, String indent) { List<Thread> threadToReturn = new ArrayList<Thread>(); log.error(indent + "Group[" + group.getName() + ":" + group.getClass() + "]"); int nt = group.activeCount(); Thread[] threads = new Thread[nt * 2 + 10]; //nt is not accurate nt = group.enumerate(threads, false); // List every thread in the group for (int i = 0; i < nt; i++) { Thread t = threads[i]; log.error(indent + " Thread[" + t.getName() + ":" + t.getClass() + ":" + (t.getContextClassLoader() == null ? "null cl" : t.getContextClassLoader().getClass().getName() + " " + t.getContextClassLoader().hashCode()) + "]"); threadToReturn.add(t);/*from w w w . j a v a2 s . c o m*/ } // Recursively list all subgroups int ng = group.activeGroupCount(); ThreadGroup[] groups = new ThreadGroup[ng * 2 + 10]; ng = group.enumerate(groups, false); for (int i = 0; i < ng; i++) { threadToReturn.addAll(listThreads(groups[i], indent + " ")); } return threadToReturn; }
From source file:Main.java
ThreadDemo() { Thread t = new Thread(this); t.start();//from www. j av a2 s . c om 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: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()); }/* w ww .j a v a2 s .co m*/ } }
From source file:net.sf.jasperreports.ant.JavaflowRewriteTask.java
@Override public void execute() throws BuildException { Thread thread = Thread.currentThread(); ClassLoader originalClassLoader = thread.getContextClassLoader(); try {//from w w w .ja v a 2 s . co m //javaflow's ContinuationMethodAnalyzer uses the thread classloader to resolve classes thread.setContextClassLoader(getClass().getClassLoader()); super.execute(); } finally { thread.setContextClassLoader(originalClassLoader); } }