List of usage examples for java.lang Thread getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
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; }// ww w.jav a 2 s .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:org.allcolor.yahp.converter.CClassLoader.java
/** * destroy the loader tree/* w ww. j a va 2 s .co m*/ */ public static final void destroy() { if (CClassLoader.rootLoader == null) { return; } System.out.println("Destroying YAHP ClassLoader Tree"); CClassLoader.urlLoader = null; try { Field f = Class.forName("java.lang.Shutdown").getDeclaredField("hooks"); f.setAccessible(true); ArrayList l = (ArrayList) f.get(null); for (Iterator it = l.iterator(); it.hasNext();) { Object o = it.next(); if ((o != null) && (o.getClass().getClassLoader() != null) && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) { it.remove(); } } } catch (Throwable ignore) { } try { Field f = Class.forName("java.lang.ApplicationShutdownHooks").getDeclaredField("hooks"); f.setAccessible(true); IdentityHashMap l = (IdentityHashMap) f.get(null); for (Iterator it = l.entrySet().iterator(); it.hasNext();) { Entry e = (Entry) it.next(); Thread o = (Thread) e.getKey(); if ((o != null) && (o.getClass().getClassLoader() != null) && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) { it.remove(); continue; } o = (Thread) e.getValue(); if ((o != null) && (o.getClass().getClassLoader() != null) && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) { it.remove(); } } } catch (Throwable ignore) { } try { if ((UIManager.getLookAndFeel() != null) && (UIManager.getLookAndFeel().getClass().getClassLoader() != null) && (UIManager.getLookAndFeel().getClass().getClassLoader().getClass() == CClassLoader.class)) { UIManager.setLookAndFeel((LookAndFeel) null); } Field f = UIManager.class.getDeclaredField("currentLAFState"); f.setAccessible(true); Object lafstate = f.get(null); if (lafstate != null) { Field fmultiUIDefaults = lafstate.getClass().getDeclaredField("multiUIDefaults"); fmultiUIDefaults.setAccessible(true); Object multiUIDefaults = fmultiUIDefaults.get(lafstate); Method clear = multiUIDefaults.getClass().getDeclaredMethod("clear", (Class[]) null); clear.setAccessible(true); clear.invoke(multiUIDefaults, (Object[]) null); Field tbl = lafstate.getClass().getDeclaredField("tables"); tbl.setAccessible(true); Hashtable[] tables = (Hashtable[]) tbl.get(lafstate); if (tables != null) { for (int i = 0; i < tables.length; i++) { Hashtable element = tables[i]; if (element != null) { element.clear(); } } } } } catch (Throwable ignore) { } try { Hashtable tb = UIManager.getDefaults(); Object cl = tb.get("ClassLoader"); if (cl.getClass() == CClassLoader.class) { tb.put("ClassLoader", CClassLoader.rootLoader.getParent()); } } catch (Throwable ignore) { } Method logFactoryRelease = null; try { logFactoryRelease = CClassLoader.rootLoader.loadClass("org.apache.commons.logging.LogFactory") .getMethod("release", new Class[] { ClassLoader.class }); } catch (final Throwable ignore) { } CClassLoader.rootLoader._destroy(logFactoryRelease); CClassLoader.mandatoryLoadersMap.clear(); CClassLoader.rootLoader = null; // deregister any sql driver loaded try { final List deregisterList = new ArrayList(); for (final Enumeration it = DriverManager.getDrivers(); it.hasMoreElements();) { final Driver d = (Driver) it.nextElement(); if ((d != null) && (d.getClass().getClassLoader() != null) && (d.getClass().getClassLoader().getClass() == CClassLoader.class)) { deregisterList.add(d); } } for (int i = 0; i < deregisterList.size(); i++) { final Driver driver = (Driver) deregisterList.get(i); DriverManager.deregisterDriver(driver); } } catch (final Throwable ignore) { } // stop dandling thread created with this classloader // tested only on sun jdk ThreadGroup tg = Thread.currentThread().getThreadGroup(); while ((tg != null) && (tg.getParent() != null)) { tg = tg.getParent(); } List ltg = new ArrayList(); ltg.add(tg); CClassLoader.getThreadGroups(tg, ltg); for (int ii = 0; ii < ltg.size(); ii++) { try { final ThreadGroup g = (ThreadGroup) ltg.get(ii); final Field fthreads = ThreadGroup.class.getDeclaredField("threads"); fthreads.setAccessible(true); final List toStop = new ArrayList(); Object threads[] = null; if (fthreads.getType() == Vector.class) { // in gnu classpath threads = ((Vector) fthreads.get(g)).toArray(); } else { // sun threads = (Object[]) fthreads.get(g); } for (int i = 0; i < threads.length; i++) { if (threads[i] == null) { continue; } if ((threads[i] != null) && (((Thread) threads[i]).getContextClassLoader() != null) && (((Thread) threads[i]).getContextClassLoader().getClass() == CClassLoader.class)) { ((Thread) threads[i]).setContextClassLoader(null); } if ((threads[i] != null) && (threads[i].getClass().getClassLoader() != null) && (threads[i].getClass().getClassLoader().getClass() == CClassLoader.class)) { toStop.add((Thread) threads[i]); } // remove any object in threadLocal referring an object // loaded // by this classloader tree try { final Field fthreadLocals = Thread.class.getDeclaredField("threadLocals"); fthreadLocals.setAccessible(true); final Object threadLocals = fthreadLocals.get(threads[i]); if (threadLocals != null) { final Field ftable = threadLocals.getClass().getDeclaredField("table"); ftable.setAccessible(true); final Object table[] = (Object[]) ftable.get(threadLocals); for (int kk = 0; kk < table.length; kk++) { final Object element = table[kk]; if (element != null) { final Field fvalue = element.getClass().getDeclaredField("value"); fvalue.setAccessible(true); final Object value = fvalue.get(element); if ((value != null) && (value.getClass().getClassLoader() != null) && (value .getClass().getClassLoader().getClass() == CClassLoader.class)) { fvalue.set(element, null); } if (value instanceof Map) { clearMap((Map) value); } else if (value instanceof List) { clearList((List) value); } else if (value instanceof Set) { clearSet((Set) value); } else if (value instanceof Object[]) { clearArray((Object[]) value); } fvalue.setAccessible(false); } } ftable.setAccessible(false); } fthreadLocals.setAccessible(false); } catch (final Throwable ignore) { ignore.printStackTrace(); } // remove any object in threadLocal referring an object // loaded // by this classloader tree try { final Field fthreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); fthreadLocals.setAccessible(true); final Object threadLocals = fthreadLocals.get(threads[i]); if (threadLocals != null) { final Field ftable = threadLocals.getClass().getDeclaredField("table"); ftable.setAccessible(true); final Object table[] = (Object[]) ftable.get(threadLocals); for (int kk = 0; kk < table.length; kk++) { final Object element = table[kk]; if (element != null) { final Field fvalue = element.getClass().getDeclaredField("value"); fvalue.setAccessible(true); final Object value = fvalue.get(element); if ((value != null) && (value.getClass().getClassLoader() != null) && (value .getClass().getClassLoader().getClass() == CClassLoader.class)) { fvalue.set(element, null); } if (value instanceof Map) { clearMap((Map) value); } else if (value instanceof List) { clearList((List) value); } else if (value instanceof Set) { clearSet((Set) value); } else if (value instanceof Object[]) { clearArray((Object[]) value); } fvalue.setAccessible(false); } } ftable.setAccessible(false); } fthreadLocals.setAccessible(false); } catch (final Throwable ignore) { ignore.printStackTrace(); } // remove any protection domain referring this loader tree try { final Field finheritedAccessControlContext = Thread.class .getDeclaredField("inheritedAccessControlContext"); finheritedAccessControlContext.setAccessible(true); final Object inheritedAccessControlContext = finheritedAccessControlContext.get(threads[i]); if (inheritedAccessControlContext != null) { final Field fcontext = AccessControlContext.class.getDeclaredField("context"); fcontext.setAccessible(true); final Object context[] = (Object[]) fcontext.get(inheritedAccessControlContext); if (context != null) { for (int k = 0; k < context.length; k++) { if (context[k] == null) continue; final Field fclassloader = ProtectionDomain.class .getDeclaredField("classloader"); fclassloader.setAccessible(true); final Object classloader = fclassloader.get(context[k]); if ((classloader != null) && (classloader.getClass() == CClassLoader.class)) { context[k] = null; } fclassloader.setAccessible(false); } } fcontext.setAccessible(false); } finheritedAccessControlContext.setAccessible(false); } catch (final Throwable ignore) { ignore.printStackTrace(); } } fthreads.setAccessible(false); for (int i = 0; i < toStop.size(); i++) { try { final Thread t = (Thread) toStop.get(i); final Method stop = t.getClass().getMethod("stop", (Class[]) null); stop.invoke(t, (Object[]) null); } catch (final Throwable ignore) { } } } catch (final Throwable ignore) { } } try { CThreadContext.destroy(); } catch (Throwable ignore) { } System.runFinalization(); System.gc(); Introspector.flushCaches(); System.out.println("Destroying YAHP ClassLoader Tree : done"); }
From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java
/** * Deregister shutdown hook and execute it immediately *///w w w . j av a 2 s . c o m @SuppressWarnings("deprecation") protected void removeShutdownHook(Thread shutdownHook) { final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName(); error("Removing shutdown hook: " + displayString); Runtime.getRuntime().removeShutdownHook(shutdownHook); if (executeShutdownHooks) { // Shutdown hooks should be executed info("Executing shutdown hook now: " + displayString); // Make sure it's from this web app instance shutdownHook.start(); // Run cleanup immediately if (shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish try { shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run } catch (InterruptedException e) { // Do nothing } if (shutdownHook.isAlive()) { warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!"); shutdownHook.stop(); } } } }
From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java
protected void stopTimerThread(Thread thread) { // Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel() /**//from w w w. j av a 2 s . c o m try { Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work! warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'"); timer.cancel(); } catch (IllegalAccessException iaex) { error(iaex); } */ try { final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled"); final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue final Method clear = queue.getClass().getDeclaredMethod("clear"); clear.setAccessible(true); // Do what java.util.Timer.cancel() does //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queue) { newTasksMayBeScheduled.set(thread, false); clear.invoke(queue); queue.notify(); // "In case queue was already empty." } // We shouldn't need to join() here, thread will finish soon enough } catch (Exception ex) { error(ex); } }
From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java
/** * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads() *//* w w w.j a v a 2 s .c om*/ @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:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java
/** * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads() *///from w w w .ja v a2s .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:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java
protected void stopTimerThread(Thread thread) { // Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel() /** // ww w.j a v a2 s. c om try { Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work! warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'"); timer.cancel(); } catch (IllegalAccessException iaex) { error(iaex); } */ try { final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled"); final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue final Method clear = queue.getClass().getDeclaredMethod("clear"); clear.setAccessible(true); // Do what java.util.Timer.cancel() does //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queue) { newTasksMayBeScheduled.set(thread, false); clear.invoke(queue); queue.notify(); // "In case queue was already empty." } // We shouldn't need to join() here, thread will finish soon enough } catch (Exception ex) { error(ex); } }
From source file:com.newsrob.EntryManager.java
public void cancel() { cancelRequested = true;//from w ww . j ava2 s . co m if (currentRunningJob != null) currentRunningJob.cancel(); fireStatusUpdated(); if (runningThread != null) { final Thread t = new Thread(new Runnable() { public void run() { try { if (!runningThread.isAlive()) return; runningThread.join(8000); if (!runningThread.isAlive()) return; runningThread.interrupt(); runningThread.join(2500); if (!runningThread.isAlive()) return; } catch (final Throwable t) { PL.log("CANCEL: " + t.getMessage() + " " + t.getClass(), ctx); } finally { if (runningThread == null || !runningThread.isAlive()) { runningThread = null; // NOPMD by mkamp on 1/18/10 // 8:29 PM clearCancelState(); } else { PL.log("CANCEL: Didn't work out ;-( " + runningThread.getState(), ctx); for (final StackTraceElement ste : new ArrayList<StackTraceElement>( Arrays.asList(runningThread.getStackTrace()))) { PL.log("CANCEL: " + ste.toString(), ctx); } } } } }); t.start(); } }
From source file:com.grazerss.EntryManager.java
public void cancel() { cancelRequested = true;/* w w w .ja v a 2 s.co m*/ if (currentRunningJob != null) { currentRunningJob.cancel(); } fireStatusUpdated(); if (runningThread != null) { final Thread t = new Thread(new Runnable() { public void run() { try { if (!runningThread.isAlive()) { return; } runningThread.join(8000); if (!runningThread.isAlive()) { return; } runningThread.interrupt(); runningThread.join(2500); if (!runningThread.isAlive()) { return; } } catch (final Throwable t) { PL.log("CANCEL: " + t.getMessage() + " " + t.getClass(), ctx); } finally { if ((runningThread == null) || !runningThread.isAlive()) { runningThread = null; // NOPMD by mkamp on 1/18/10 // 8:29 PM clearCancelState(); } else { PL.log("CANCEL: Didn't work out ;-( " + runningThread.getState(), ctx); for (final StackTraceElement ste : new ArrayList<StackTraceElement>( Arrays.asList(runningThread.getStackTrace()))) { PL.log("CANCEL: " + ste.toString(), ctx); } } } } }); t.start(); } }