List of usage examples for java.lang.management ThreadMXBean getAllThreadIds
public long[] getAllThreadIds();
From source file:org.apache.tajo.master.querymaster.QueryMasterRunner.java
public static void printThreadInfo(PrintWriter stream, String title) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); final int STACK_DEPTH = 60; boolean contention = threadBean.isThreadContentionMonitoringEnabled(); long[] threadIds = threadBean.getAllThreadIds(); stream.println("Process Thread Dump: " + title); stream.println(threadIds.length + " active threads"); for (long tid : threadIds) { ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH); if (info == null) { stream.println(" Inactive"); continue; }/* w ww. ja va2s. com*/ stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":"); Thread.State state = info.getThreadState(); stream.println(" State: " + state); stream.println(" Blocked count: " + info.getBlockedCount()); stream.println(" Waited count: " + info.getWaitedCount()); if (contention) { stream.println(" Blocked time: " + info.getBlockedTime()); stream.println(" Waited time: " + info.getWaitedTime()); } if (state == Thread.State.WAITING) { stream.println(" Waiting on " + info.getLockName()); } else if (state == Thread.State.BLOCKED) { stream.println(" Blocked on " + info.getLockName()); stream.println(" Blocked by " + getTaskName(info.getLockOwnerId(), info.getLockOwnerName())); } stream.println(" Stack:"); for (StackTraceElement frame : info.getStackTrace()) { stream.println(" " + frame.toString()); } } stream.flush(); }
From source file:org.apache.tez.runtime.LogicalIOProcessorRuntimeTask.java
/** * Print all threads in JVM (only for debugging) *///from w ww. ja v a 2 s. c o m void printThreads() { //Print the status of all threads in JVM ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadMXBean.getAllThreadIds(); for (Long id : threadIds) { ThreadInfo threadInfo = threadMXBean.getThreadInfo(id); // The thread could have been shutdown before we read info about it. if (threadInfo != null) { if (LOG.isDebugEnabled()) { LOG.debug("ThreadId : " + id + ", name=" + threadInfo.getThreadName()); } } } }
From source file:org.commonjava.indy.diag.data.DiagnosticsManager.java
public String getThreadDumpString() { Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads);/*from www. ja v a 2 s. c o m*/ Map<Long, Thread> threadMap = new HashMap<>(); Stream.of(threads).forEach(t -> threadMap.put(t.getId(), t)); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); StringBuilder sb = new StringBuilder(); Stream.of(threadInfos).forEachOrdered((ti) -> { if (sb.length() > 0) { sb.append("\n\n"); } String threadGroup = "Unknown"; Thread t = threadMap.get(ti.getThreadId()); if (t != null) { ThreadGroup tg = t.getThreadGroup(); if (tg != null) { threadGroup = tg.getName(); } } sb.append(ti.getThreadName()).append("\n Group: ").append(threadGroup).append("\n State: ") .append(ti.getThreadState()).append("\n Lock Info: ").append(ti.getLockInfo()) .append("\n Monitors:"); MonitorInfo[] monitors = ti.getLockedMonitors(); if (monitors == null || monitors.length < 1) { sb.append(" -NONE-"); } else { sb.append("\n - ").append(join(monitors, "\n - ")); } sb.append("\n Trace:\n ").append(join(ti.getStackTrace(), "\n ")); }); return sb.toString(); }
From source file:org.commonjava.indy.ftest.core.fixture.ThreadDumper.java
public static void dumpThreads() { StringBuilder sb = new StringBuilder(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); Stream.of(threadInfos).forEachOrdered((ti) -> { if (sb.length() > 0) { sb.append("\n\n"); }//from w ww . j a v a2 s .c om sb.append(ti.getThreadName()).append("\n State: ").append(ti.getThreadState()) .append("\n Lock Info: ").append(ti.getLockInfo()).append("\n Monitors:"); MonitorInfo[] monitors = ti.getLockedMonitors(); if (monitors == null || monitors.length < 1) { sb.append(" -NONE-"); } else { sb.append("\n - ").append(join(monitors, "\n - ")); } sb.append("\n Trace:\n ").append(join(ti.getStackTrace(), "\n ")); }); System.out.println(sb); }
From source file:org.jitsi.meet.test.base.FailureListener.java
/** * Saves current java thread dump./* w w w .j a v a 2 s . com*/ */ private void saveThreadDump(String fileNamePrefix) { StringBuilder dump = new StringBuilder(); ThreadMXBean tbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threads = tbean.getThreadInfo(tbean.getAllThreadIds(), 150); for (ThreadInfo tinfo : threads) { dump.append(tinfo); dump.append("\n"); } try { BufferedWriter out = new BufferedWriter( new FileWriter(new File(outputLogsParentFolder, fileNamePrefix + ".tdump"))); out.write(dump.toString()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.jitsi.meet.test.FailureListener.java
/** * Saves current java thread dump.//from w w w . j a v a2s . c o m */ private void saveThreadDump(String fileNamePrefix) { StringBuilder dump = new StringBuilder(); ThreadMXBean tbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threads = tbean.getThreadInfo(tbean.getAllThreadIds(), 150); for (ThreadInfo tinfo : threads) { dump.append(tinfo); dump.append("\n"); } try { BufferedWriter out = new BufferedWriter( new FileWriter(new File(outputLogsParentFolder, fileNamePrefix + ".tdump"))); out.write(dump.toString()); out.flush(); out.close(); } catch (IOException e) { } }
From source file:org.jumpmind.symmetric.util.SnapshotUtil.java
public static File createSnapshot(ISymmetricEngine engine) { String dirName = engine.getEngineName().replaceAll(" ", "-") + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); IParameterService parameterService = engine.getParameterService(); File tmpDir = new File(parameterService.getTempDirectory(), dirName); tmpDir.mkdirs();/*from w w w.j a v a2 s .co m*/ File logDir = null; String parameterizedLogDir = parameterService.getString("server.log.dir"); if (isNotBlank(parameterizedLogDir)) { logDir = new File(parameterizedLogDir); } if (logDir != null && logDir.exists()) { log.info("Using server.log.dir setting as the location of the log files"); } else { logDir = new File("logs"); if (!logDir.exists()) { File file = findSymmetricLogFile(); if (file != null) { logDir = file.getParentFile(); } } if (!logDir.exists()) { logDir = new File("../logs"); } if (!logDir.exists()) { logDir = new File("target"); } if (logDir.exists()) { File[] files = logDir.listFiles(); if (files != null) { for (File file : files) { if (file.getName().toLowerCase().endsWith(".log")) { try { FileUtils.copyFileToDirectory(file, tmpDir); } catch (IOException e) { log.warn("Failed to copy " + file.getName() + " to the snapshot directory", e); } } } } } } ITriggerRouterService triggerRouterService = engine.getTriggerRouterService(); List<TriggerHistory> triggerHistories = triggerRouterService.getActiveTriggerHistories(); TreeSet<Table> tables = new TreeSet<Table>(); for (TriggerHistory triggerHistory : triggerHistories) { Table table = engine.getDatabasePlatform().getTableFromCache(triggerHistory.getSourceCatalogName(), triggerHistory.getSourceSchemaName(), triggerHistory.getSourceTableName(), false); if (table != null && !table.getName().toUpperCase() .startsWith(engine.getSymmetricDialect().getTablePrefix().toUpperCase())) { tables.add(table); } } List<Trigger> triggers = triggerRouterService.getTriggers(true); for (Trigger trigger : triggers) { Table table = engine.getDatabasePlatform().getTableFromCache(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger.getSourceTableName(), false); if (table != null) { tables.add(table); } } FileWriter fwriter = null; try { fwriter = new FileWriter(new File(tmpDir, "config-export.csv")); engine.getDataExtractorService().extractConfigurationStandalone(engine.getNodeService().findIdentity(), fwriter, TableConstants.SYM_NODE, TableConstants.SYM_NODE_SECURITY, TableConstants.SYM_NODE_IDENTITY, TableConstants.SYM_NODE_HOST, TableConstants.SYM_NODE_CHANNEL_CTL, TableConstants.SYM_CONSOLE_USER); } catch (IOException e) { log.warn("Failed to export symmetric configuration", e); } finally { IOUtils.closeQuietly(fwriter); } FileOutputStream fos = null; try { fos = new FileOutputStream(new File(tmpDir, "table-definitions.xml")); DbExport export = new DbExport(engine.getDatabasePlatform()); export.setFormat(Format.XML); export.setNoData(true); export.exportTables(fos, tables.toArray(new Table[tables.size()])); } catch (IOException e) { log.warn("Failed to export table definitions", e); } finally { IOUtils.closeQuietly(fos); } String tablePrefix = engine.getTablePrefix(); DbExport export = new DbExport(engine.getDatabasePlatform()); export.setFormat(Format.CSV); export.setNoCreateInfo(true); extract(export, new File(tmpDir, "identity.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_IDENTITY)); extract(export, new File(tmpDir, "node.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE)); extract(export, new File(tmpDir, "nodesecurity.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_SECURITY)); extract(export, new File(tmpDir, "nodehost.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_HOST)); extract(export, new File(tmpDir, "triggerhist.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_TRIGGER_HIST)); extract(export, new File(tmpDir, "lock.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_LOCK)); extract(export, new File(tmpDir, "nodecommunication.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_COMMUNICATION)); extract(export, 5000, new File(tmpDir, "outgoingbatch.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_OUTGOING_BATCH)); extract(export, 5000, new File(tmpDir, "incomingbatch.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_INCOMING_BATCH)); final int THREAD_INDENT_SPACE = 50; fwriter = null; try { fwriter = new FileWriter(new File(tmpDir, "threads.txt")); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadBean.getAllThreadIds(); for (long l : threadIds) { ThreadInfo info = threadBean.getThreadInfo(l, 100); if (info != null) { String threadName = info.getThreadName(); fwriter.append(StringUtils.rightPad(threadName, THREAD_INDENT_SPACE)); StackTraceElement[] trace = info.getStackTrace(); boolean first = true; for (StackTraceElement stackTraceElement : trace) { if (!first) { fwriter.append(StringUtils.rightPad("", THREAD_INDENT_SPACE)); } else { first = false; } fwriter.append(stackTraceElement.getClassName()); fwriter.append("."); fwriter.append(stackTraceElement.getMethodName()); fwriter.append("()"); int lineNumber = stackTraceElement.getLineNumber(); if (lineNumber > 0) { fwriter.append(": "); fwriter.append(Integer.toString(stackTraceElement.getLineNumber())); } fwriter.append("\n"); } fwriter.append("\n"); } } } catch (IOException e) { log.warn("Failed to export thread information", e); } finally { IOUtils.closeQuietly(fwriter); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "parameters.properties")); Properties effectiveParameters = engine.getParameterService().getAllParameters(); SortedProperties parameters = new SortedProperties(); parameters.putAll(effectiveParameters); parameters.remove("db.password"); parameters.store(fos, "parameters.properties"); } catch (IOException e) { log.warn("Failed to export parameter information", e); } finally { IOUtils.closeQuietly(fos); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "parameters-changed.properties")); Properties defaultParameters = new Properties(); InputStream in = SnapshotUtil.class.getResourceAsStream("/symmetric-default.properties"); defaultParameters.load(in); IOUtils.closeQuietly(in); in = SnapshotUtil.class.getResourceAsStream("/symmetric-console-default.properties"); if (in != null) { defaultParameters.load(in); IOUtils.closeQuietly(in); } Properties effectiveParameters = engine.getParameterService().getAllParameters(); Properties changedParameters = new SortedProperties(); Map<String, ParameterMetaData> parameters = ParameterConstants.getParameterMetaData(); for (String key : parameters.keySet()) { String defaultValue = defaultParameters.getProperty((String) key); String currentValue = effectiveParameters.getProperty((String) key); if (defaultValue == null && currentValue != null || (defaultValue != null && !defaultValue.equals(currentValue))) { changedParameters.put(key, currentValue == null ? "" : currentValue); } } changedParameters.remove("db.password"); changedParameters.store(fos, "parameters-changed.properties"); } catch (IOException e) { log.warn("Failed to export parameters-changed information", e); } finally { IOUtils.closeQuietly(fos); } writeRuntimeStats(engine, tmpDir); writeJobsStats(engine, tmpDir); if ("true".equals(System.getProperty(SystemConstants.SYSPROP_STANDALONE_WEB))) { writeDirectoryListing(engine, tmpDir); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "system.properties")); SortedProperties props = new SortedProperties(); props.putAll(System.getProperties()); props.store(fos, "system.properties"); } catch (IOException e) { log.warn("Failed to export thread information", e); } finally { IOUtils.closeQuietly(fos); } try { File jarFile = new File(getSnapshotDirectory(engine), tmpDir.getName() + ".zip"); JarBuilder builder = new JarBuilder(tmpDir, jarFile, new File[] { tmpDir }, Version.version()); builder.build(); FileUtils.deleteDirectory(tmpDir); return jarFile; } catch (IOException e) { throw new IoException("Failed to package snapshot files into archive", e); } }
From source file:org.wso2.carbon.integration.test.client.JMXAnalyzerClient.java
public static int getThreadCount(String host, String port) throws IOException { String username = "admin"; String password = "admin"; int threadCount = 0; String threadName = "JMSThreads"; JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi"); Map<String, String[]> env = new HashMap<String, String[]>(); ThreadInfo threadIDInfo;/*from ww w.j a v a2 s.c o m*/ String[] credentials = { username, password }; env.put(JMXConnector.CREDENTIALS, credentials); JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env); MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection(); final ThreadMXBean remoteThread = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConnection, ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class); long[] allThreadIDsArray = remoteThread.getAllThreadIds(); //get jms thread count for (long threadID : allThreadIDsArray) { threadIDInfo = remoteThread.getThreadInfo(threadID); if (threadIDInfo != null && threadIDInfo.getThreadName() != null && threadIDInfo.getThreadName().startsWith(threadName)) { threadCount++; } } //close the connection jmxConnector.close(); return threadCount; }
From source file:org.wyona.yanel.impl.resources.usecase.thread.UsecaseThread.java
/** * Get thread with the given id from repository. * @param repository Repository/*w w w.j a v a2 s. co m*/ * @param directoryPath Collection path which contains the thread key * @param threadID * @return thread or null if there is no such thread attached to the repository */ public static java.lang.management.ThreadInfo getThreadFromRepository( org.wyona.yarep.core.Repository repository, String directoryPath, String threadID) throws org.wyona.yarep.core.RepositoryException, java.io.IOException { //public static UsecaseThread getThreadFromRepository(org.wyona.yarep.core.Repository repository, String directoryPath, String threadID) throws org.wyona.yarep.core.RepositoryException, java.io.IOException { String threadKey = getThreadKey(threadID); String threadKeyPath = directoryPath + "/" + threadKey; if (repository.existsNode(threadKeyPath)) { Node node = repository.getNode(threadKeyPath); String javaThreadId = new java.io.BufferedReader(new java.io.InputStreamReader(node.getInputStream())) .readLine(); final java.lang.management.ThreadMXBean thbean = java.lang.management.ManagementFactory .getThreadMXBean(); long[] threadIDs = thbean.getAllThreadIds(); for (int i = 0; i < threadIDs.length; i++) { log.debug("Thread ID: " + threadIDs[i]); if (javaThreadId.equals("" + threadIDs[i])) { log.debug("Thread with id '" + javaThreadId + "' is running."); return thbean.getThreadInfo(threadIDs[i]); /* final Thread[] threads = getAllThreads(); for (Thread thread : threads) { if (thread.getId() == threadIDs[i]) { return (UsecaseThread) thread; } } log.error("No thread with id '" + threadIDs[i] + "' exists!"); return null; */ } } log.info("No such thread running: " + threadID + ", " + javaThreadId); return null; } else { log.info("No such thread '" + threadID + "' within repository: " + threadKeyPath); return null; } //return (UsecaseThread)session.getAttribute(attrName); }
From source file:rpc.TestRPC.java
/** * Count the number of threads that have a stack frame containing the given * string/*from w w w . j a va 2 s . c om*/ */ private static int countThreads(String search) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int count = 0; ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20); for (ThreadInfo info : infos) { if (info == null) continue; for (StackTraceElement elem : info.getStackTrace()) { if (elem.getClassName().contains(search)) { count++; break; } } } return count; }