synchronized boolean hasActiveNonDaemonThreads() { if (runningThreads.isEmpty() && newThreads.isEmpty()) return false; for (Thread t : runningThreads) { if (t.isDaemon()) continue; return true; } for (Thread t : newThreads) { if (t.isDaemon()) continue; return true; } return false; }
@Test public void testThreadDetails() { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); SingleThreadEventExecutor executor = new SingleThreadEventExecutor(null, Executors.newCachedThreadPool(), false) { @Override protected void run() { threadRef.set(Thread.currentThread()); while (!confirmShutdown()) { Runnable task = takeTask(); if (task != null) { task.run(); } } } }; ThreadProperties threadProperties = executor.threadProperties(); Assert.assertSame(threadProperties, executor.threadProperties()); Thread thread = threadRef.get(); Assert.assertEquals(thread.getId(), threadProperties.id()); Assert.assertEquals(thread.getName(), threadProperties.name()); Assert.assertEquals(thread.getPriority(), threadProperties.priority()); Assert.assertEquals(thread.getState(), threadProperties.state()); Assert.assertEquals(thread.isAlive(), threadProperties.isAlive()); Assert.assertEquals(thread.isDaemon(), threadProperties.isDaemon()); Assert.assertEquals(thread.isInterrupted(), threadProperties.isInterrupted()); Assert.assertTrue(threadProperties.stackTrace().length > 0); executor.shutdownGracefully(); }
private static String getStackTracesAsString() { Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); Thread[] threads = allStackTraces.keySet().toArray(new Thread[0]); Arrays.sort( threads, new Comparator<Thread>() { public int compare(Thread o1, Thread o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); StringBuilder sb = new StringBuilder(); for (Thread t : threads) { sb.append((t.isDaemon() ? "Daemon Thread [" : "Thread [")) .append(t.getName()) .append("] (") .append(t.getState()) .append(")") .append(LINE_SEPARATOR); StackTraceElement[] stackTraceElements = allStackTraces.get(t); for (StackTraceElement stackTraceElement : stackTraceElements) { sb.append("\tat ").append(stackTraceElement).append(LINE_SEPARATOR); } } return sb.toString(); }
@Override public Thread newThread(Runnable r) { Thread t = new Thread(r, mPrefix + "-" + mPoolNum + "-Thread-" + mThreadNum.incrementAndGet()); if (t.isDaemon() != mIsDaemon) t.setDaemon(mIsDaemon); return t; }
@SuppressWarnings("deprecation") public void stop_Event() { System.out.println("Stop"); stop = true; pause = true; if (playThreadAnimation != null && (playThreadAnimation.isAlive() || playThreadAnimation.isDaemon())) playThreadAnimation.stop(); ISourceProviderService service = (ISourceProviderService) getSite().getService(ISourceProviderService.class); DebugToolsCommandSourceProvider sourceProvider = (DebugToolsCommandSourceProvider) service.getSourceProvider(DebugToolsCommandSourceProvider.PLAY_COMMAND_STATE); sourceProvider.setPlayState(true); sourceProvider.setStopState(false); sourceProvider.setPauseState(false); sourceProvider.setStepState(false); IWorkbenchPage page = getSite().getPage(); System.out.println("page:" + page); if (page != null) { IPerspectiveDescriptor perspective = page.getPerspective(); if (perspective != null) { page.closePerspective(perspective, false, true); } } }
@Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); t.setPriority(threadPriority); return t; }
public static void dumpThreads(ThreadGroup threadGroup, String indent) { Thread[] threadList = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(threadList); for (int i = 0; i < threadList.length; i++) { Thread t = threadList[i]; if (t != null) { out( indent .concat("active thread = ") .concat(t.toString()) .concat(", daemon = ") .concat(String.valueOf(t.isDaemon()))); } } if (threadGroup.getParent() != null) { dumpThreads(threadGroup.getParent(), indent + "\t"); } }
public Thread newThread(Runnable r) { Thread t = new GSThread(group, r, namePrefix + threadNumber.get(), threadNumber.getAndIncrement()); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.MAX_PRIORITY) t.setPriority(Thread.MAX_PRIORITY); return t; }
@Override public void run() { boolean loop = true; try { while (loop) { final Thread[] all = new Thread[Thread.activeCount() + 100]; final int count = Thread.enumerate(all); loop = false; for (int i = 0; i < count; i++) { final Thread t = all[i]; // daemon: skip it. if (t.isDaemon()) continue; // RMI Reaper: skip it. if (t.getName().startsWith("RMI Reaper")) continue; if (t.getName().startsWith("DestroyJavaVM")) continue; // Non daemon, non RMI Reaper: join it, break the for // loop, continue in the while loop (loop=true) loop = true; try { // Found a non-daemon thread. Wait for it. t.join(); } catch (Exception ex) { ex.printStackTrace(); } break; } } // We went through a whole for-loop without finding any thread // to join. We can close cs. } catch (Exception ex) { ex.printStackTrace(); } finally { try { // if we reach here it means the only non-daemon threads // that remain are reaper threads - or that we got an // unexpected exception/error. // if (cs != null && cs.isActive()) { cs.stop(); } } catch (Exception ex) { ex.printStackTrace(); } } }
public static void main(String[] args) throws Exception { Thread d = new DaemonThread(); System.out.println("d.isDaemon() = " + d.isDaemon()); // Allow the daemon threads to // finish their startup processes: Thread.sleep(1000); }
public final Thread newThread(Runnable r) { Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0); if (t.isDaemon()) { t.setDaemon(false); } t.setPriority(this.threadPriority); return t; }
public Thread newThread(final Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; }
@Override public Thread newThread(Runnable runnable) { String threadName = namePrefix + "-thread-" + threadNumber.getAndIncrement(); Thread thread = new Thread(group, runnable, threadName, 0); if (thread.isDaemon()) { thread.setDaemon(false); } thread.setPriority(threadPriority); return thread; }
@Override public Thread newThread(Runnable r) { Thread t = new Thread(null, r, "hj", 0); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; }
/** @param args */ public static void main(String[] args) { Thread d = new Thread(new Daemon()); d.setDaemon(true); d.start(); System.out.println("d.isDaemon() = " + d.isDaemon() + " ."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
public Thread newThread(Runnable r) { String name = threadName + "-" + threadNum.getAndIncrement(); Thread t = new Thread(r, name); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }
@Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); // I can't really see that we want non-daemon threads... // Seems we might get problem with daemon-threads?? Does this mess up join after invoke?? // t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }
/** Returns the non-daemon threads of a thread group. */ private Collection<Thread> getNonDaemonThreads(ThreadGroup group) { Thread[] threads = new Thread[group.activeCount()]; int count = group.enumerate(threads); Collection<Thread> nonDaemonThreads = new ArrayList<>(count); for (int i = 0; i < count; i++) { Thread thread = threads[i]; if (!thread.isDaemon()) { nonDaemonThreads.add(thread); } } return nonDaemonThreads; }
private void joinNonDaemonThreads(ThreadGroup threadGroup) { boolean foundNonDaemon; do { foundNonDaemon = false; Collection<Thread> threads = getActiveThreads(threadGroup); for (Thread thread : threads) { if (thread.isDaemon()) { continue; } foundNonDaemon = true; // try again; maybe more threads were // created while we were busy joinThread(thread, 0); } } while (foundNonDaemon); }
/** Print diagnostic information about currently running threads at warn level. */ public void threadGroupList() { Thread[] threads = new Thread[_threads.activeCount()]; _threads.enumerate(threads); for (Thread thread : threads) { LOGGER.warn( "Thread: {} [{}{}{}] ({}) {}", thread.getName(), (thread.isAlive() ? "A" : "-"), (thread.isDaemon() ? "D" : "-"), (thread.isInterrupted() ? "I" : "-"), thread.getPriority(), thread.getState()); for (StackTraceElement s : thread.getStackTrace()) { LOGGER.warn(" {}", s); } } }
private static final List<Thread> getNonDaemonThreads() { List<Thread> res = new ArrayList<Thread>(); int[] tn = {0}; Thread[] threads = getAllThreads(tn); for (int i = tn[0] - 1; i >= 0; i--) { final Thread thread = threads[i]; try { if (thread.isAlive() && !thread.isDaemon()) { res.add(thread); if (DEBUG) System.err.println("XXX0: " + thread.getName() + ", " + thread); } } catch (Throwable t) { t.printStackTrace(); } } return res; }
private static void threadInfo(final Thread t, final StringBuilder sb) { sb.append("\""); sb.append(t.getName()); sb.append("\""); if (!t.isAlive()) sb.append(" DEAD"); if (t.isInterrupted()) sb.append(" INTERRUPTED"); if (t.isDaemon()) sb.append(" daemon"); sb.append(" prio="); sb.append(t.getPriority()); sb.append(" id="); sb.append(t.getId()); sb.append(" group="); sb.append(t.getThreadGroup().getName()); sb.append(NL); sb.append(" java.lang.Thread.State: "); sb.append(t.getState()); sb.append(NL); }
@Override public Thread newThread(final Runnable runnable) { synchronized (this.threadNumber) { if (this.group == null) { this.threadNamePrefix = this.namePrefix + "-thread-"; this.group = new ThreadGroup(this.parentGroup, this.namePrefix); } } final String threadName = this.threadNamePrefix + this.threadNumber.getAndIncrement(); final LoggingRunnable loggingRunnable = new LoggingRunnable(runnable); final Thread thread = new Thread(this.group, loggingRunnable, threadName, 0); if (thread.isDaemon()) { thread.setDaemon(false); } thread.setPriority(this.priority); return thread; }
private static final int getNonDaemonThreadCount(List<Thread> ignoreThreads) { int res = 0; int[] tn = {0}; Thread[] threads = getAllThreads(tn); for (int i = tn[0] - 1; i >= 0; i--) { final Thread thread = threads[i]; try { if (thread.isAlive() && !thread.isDaemon() && !ignoreThreads.contains(thread)) { res++; if (DEBUG) System.err.println("MainAction.run(): non daemon thread: " + thread); } } catch (Throwable t) { t.printStackTrace(); } } return res; }
private void listThreads() { final Set<Thread> threads = Thread.getAllStackTraces().keySet(); final Map<String, Thread> sorted = Maps.newTreeMap(); for (final Thread t : threads) { final ThreadGroup tg = t.getThreadGroup(); if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) { sorted.put(t.getName(), t); } } log.info("= THREADS " + Strings.repeat("=", 70)); for (final Thread t : sorted.values()) { final ThreadGroup tg = t.getThreadGroup(); log.info( "{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "), (t.isDaemon() ? "daemon" : "")); } log.info(Strings.repeat("=", 80)); }
// Join threads, return false if only our own threads are left. private boolean joinThreads(Thread pThreads[]) { for (int i = 0; i < pThreads.length; i++) { final Thread t = pThreads[i]; if (t.isDaemon() || t.getThreadGroup().equals(threadGroup) || t.getName().startsWith("DestroyJavaVM")) { // These are threads which should not prevent the server from stopping. continue; } try { t.join(); } catch (Exception ex) { // Ignore that one. } finally { // We just joined a 'foreign' thread, so we redo the loop return true; } } // All 'foreign' threads has finished, hence we are prepared to stop return false; }
/** * Return a user friendly description of the thread. We could use Thread.toString(), but that is * hard to read. * * @param thread The thread * @return A user friendly description of the thread. */ public static String toThreadDescription(Thread thread) { String name = "Unnamed thread"; String group = "Unnamed group"; try { if (thread == null) { return "PrintThreads.toThreadDescription(): " + "thread argument == null\n " + "This can happen if the thread was " + "killed while PrintThreads was called"; } if (thread.getName() != null) { name = thread.getName(); } if ((thread.getThreadGroup() != null) && (thread.getThreadGroup().getName() != null)) { group = thread.getThreadGroup().getName(); } return _stringFormat(name, 35) + " " + _stringFormat(group, 20) + " " + _stringFormat(Integer.toString(thread.getPriority()), 3) + " " + _stringFormat(Boolean.valueOf(thread.isDaemon()).toString(), 6) + " " + _stringFormat(Boolean.valueOf(thread.isAlive()).toString(), 5) + (Thread.currentThread().equals(thread) ? " *" : " "); } catch (Exception e) { return _stringFormat(name, 35) + " " + _stringFormat(group, 20) + " " + "PrintThread.toThreadDescription(): Bad State!: " + e; } }
@SuppressWarnings("deprecation") @Override protected void runReportal() throws Exception { System.out.println("Reportal Pig: Setting up Pig"); injectAllVariables(prop.getString(PIG_SCRIPT)); String[] args = getParams(); System.out.println("Reportal Pig: Running pig script"); PrintStream oldOutputStream = System.out; File tempOutputFile = new File("./temp.out"); OutputStream tempOutputStream = new BufferedOutputStream(new FileOutputStream(tempOutputFile)); PrintStream printStream = new PrintStream(tempOutputStream); System.setOut(printStream); PigStats stats = PigRunner.run(args, null); System.setOut(oldOutputStream); printStream.close(); // convert pig output to csv and write it to disk System.out.println("Reportal Pig: Converting output"); InputStream tempInputStream = new BufferedInputStream(new FileInputStream(tempOutputFile)); Scanner rowScanner = new Scanner(tempInputStream); PrintStream csvOutputStream = new PrintStream(outputStream); while (rowScanner.hasNextLine()) { String line = rowScanner.nextLine(); // strip all quotes, and then quote the columns if (line.startsWith("(")) { line = transformDumpLine(line); } else { line = transformDescriptionLine(line); } csvOutputStream.println(line); } rowScanner.close(); csvOutputStream.close(); // Flush the temp file out tempOutputFile.delete(); if (!stats.isSuccessful()) { System.out.println("Reportal Pig: Handling errors"); File pigLogFile = new File("./"); File[] fileList = pigLogFile.listFiles(); for (File file : fileList) { if (file.isFile() && file.getName().matches("^pig_.*\\.log$")) { handleError(file); } } // see jira ticket PIG-3313. Will remove these when we use pig binary with that patch. // ///////////////////// System.out.println("Trying to do self kill, in case pig could not."); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread t : threadArray) { if (!t.isDaemon() && !t.equals(Thread.currentThread())) { System.out.println("Killing thread " + t); t.interrupt(); t.stop(); } } System.exit(1); // //////////////////// throw new ReportalRunnerException("Pig job failed."); } else { System.out.println("Reportal Pig: Ended successfully"); } }
public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (!t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }
@Override public boolean useCommand(String command, PrintWriter _print, Socket _cSocket, int _uptime) { if (command.startsWith("debug") && (command.length() > 6)) { StringTokenizer st = new StringTokenizer(command.substring(6)); // TODO: Rewrite to use ARM. FileOutputStream fos = null; OutputStreamWriter out = null; try { String dbg = st.nextToken(); if (dbg.equals("decay")) { _print.print(DecayTaskManager.getInstance().toString()); } else if (dbg.equals("packetsend")) { if (st.countTokens() < 2) { _print.println("Usage: debug packetsend <charName> <packetData>"); return false; } String charName = st.nextToken(); L2PcInstance targetPlayer = L2World.getInstance().getPlayer(charName); if (targetPlayer == null) { _print.println("Player " + charName + " cannot be found online"); return false; } AdminForgePacket sp = new AdminForgePacket(); while (st.hasMoreTokens()) { String b = st.nextToken(); if (!b.isEmpty()) { sp.addPart("C".getBytes()[0], "0x" + b); } } targetPlayer.sendPacket(sp); _print.println("Packet sent to player " + charName); } else if (dbg.equals("PacketTP")) { String str = ThreadPoolManager.getInstance().getPacketStats(); _print.println(str); int i = 0; File f = new File("./log/StackTrace-PacketTP-" + i + ".txt"); while (f.exists()) { i++; f = new File("./log/StackTrace-PacketTP-" + i + ".txt"); } f.getParentFile().mkdirs(); fos = new FileOutputStream(f); out = new OutputStreamWriter(fos, "UTF-8"); out.write(str); } else if (dbg.equals("IOPacketTP")) { String str = ThreadPoolManager.getInstance().getIOPacketStats(); _print.println(str); int i = 0; File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt"); while (f.exists()) { i++; f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt"); } f.getParentFile().mkdirs(); fos = new FileOutputStream(f); out = new OutputStreamWriter(fos, "UTF-8"); out.write(str); } else if (dbg.equals("GeneralTP")) { String str = ThreadPoolManager.getInstance().getGeneralStats(); _print.println(str); int i = 0; File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt"); while (f.exists()) { i++; f = new File("./log/StackTrace-GeneralTP-" + i + ".txt"); } f.getParentFile().mkdirs(); fos = new FileOutputStream(f); out = new OutputStreamWriter(fos, "UTF-8"); out.write(str); } else if (dbg.equals("full")) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); StringBuilder sb = new StringBuilder(); sb.append(sdf.format(cal.getTime())); sb.append("\n\n"); uptime = _uptime; sb.append(getServerStatus()); sb.append("\n\n"); sb.append("\n## Java Platform Information ##"); sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name")); sb.append("\nJava Version: " + System.getProperty("java.version")); sb.append("\nJava Class Version: " + System.getProperty("java.class.version")); sb.append('\n'); sb.append("\n## Virtual Machine Information ##"); sb.append("\nVM Name: " + System.getProperty("java.vm.name")); sb.append("\nVM Version: " + System.getProperty("java.vm.version")); sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor")); sb.append("\nVM Info: " + System.getProperty("java.vm.info")); sb.append('\n'); sb.append("\n## OS Information ##"); sb.append("\nName: " + System.getProperty("os.name")); sb.append("\nArchiteture: " + System.getProperty("os.arch")); sb.append("\nVersion: " + System.getProperty("os.version")); sb.append('\n'); sb.append("\n## Runtime Information ##"); sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors()); sb.append( "\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb"); sb.append( "\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb"); sb.append( "\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb"); sb.append('\n'); sb.append("\n## Class Path Information ##\n"); String cp = System.getProperty("java.class.path"); String[] libs = cp.split(File.pathSeparator); for (String lib : libs) { sb.append(lib); sb.append('\n'); } sb.append('\n'); sb.append("## Threads Information ##\n"); Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces(); FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<>(); entries.setValueComparator( new FastComparator<Entry<Thread, StackTraceElement[]>>() { /** */ private static final long serialVersionUID = 1L; @Override public boolean areEqual( Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) { return e1.getKey().getName().equals(e2.getKey().getName()); } @Override public int compare( Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) { return e1.getKey().getName().compareTo(e2.getKey().getName()); } @Override public int hashCodeOf(Entry<Thread, StackTraceElement[]> e) { return e.hashCode(); } }); entries.addAll(allThread.entrySet()); entries.sort(); for (Entry<Thread, StackTraceElement[]> entry : entries) { StackTraceElement[] stes = entry.getValue(); Thread t = entry.getKey(); sb.append("--------------\n"); sb.append(t.toString() + " (" + t.getId() + ")\n"); sb.append("State: " + t.getState() + '\n'); sb.append( "isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + '\n'); sb.append('\n'); for (StackTraceElement ste : stes) { sb.append(ste.toString()); sb.append('\n'); } sb.append('\n'); } sb.append('\n'); ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); long[] ids = findDeadlockedThreads(mbean); if ((ids != null) && (ids.length > 0)) { Thread[] threads = new Thread[ids.length]; for (int i = 0; i < threads.length; i++) { threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i])); } sb.append("Deadlocked Threads:\n"); sb.append("-------------------\n"); for (Thread thread : threads) { System.err.println(thread); for (StackTraceElement ste : thread.getStackTrace()) { sb.append("\t" + ste); sb.append('\n'); } } } sb.append("\n\n## Thread Pool Manager Statistics ##\n"); for (String line : ThreadPoolManager.getInstance().getStats()) { sb.append(line); sb.append('\n'); } int i = 0; File f = new File("./log/Debug-" + i + ".txt"); while (f.exists()) { i++; f = new File("./log/Debug-" + i + ".txt"); } f.getParentFile().mkdirs(); fos = new FileOutputStream(f); out = new OutputStreamWriter(fos, "UTF-8"); out.write(sb.toString()); out.flush(); out.close(); fos.close(); _print.println("Debug output saved to log/" + f.getName()); _print.flush(); } } catch (Exception e) { } finally { try { if (out != null) { out.close(); } } catch (Exception e) { } try { if (fos != null) { fos.close(); } } catch (Exception e) { } } } return false; }