List of usage examples for java.lang.management ThreadInfo getThreadName
public String getThreadName()
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; 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++;/*from www. j a v a 2 s.com*/ } } //close the connection jmxConnector.close(); return threadCount; }
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. java 2 s. com 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:backtype.storm.utils.Utils.java
public static String threadDump() { final StringBuilder dump = new StringBuilder(); final java.lang.management.ThreadMXBean threadMXBean = java.lang.management.ManagementFactory .getThreadMXBean();//from ww w . j a v a2s.c o m final java.lang.management.ThreadInfo[] threadInfos = threadMXBean .getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (java.lang.management.ThreadInfo threadInfo : threadInfos) { dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append("\" "); final Thread.State state = threadInfo.getThreadState(); dump.append("\n java.lang.Thread.State: "); dump.append(state); final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); for (final StackTraceElement stackTraceElement : stackTraceElements) { dump.append("\n at "); dump.append(stackTraceElement); } dump.append("\n\n"); } return dump.toString(); }
From source file:DeadlockDetector.java
private void printThread(ThreadInfo ti) { sb.append("\nPrintThread\n"); sb.append(//ww w. j a v a2 s .com "\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " in " + ti.getThreadState() + "\n"); if (ti.getLockName() != null) { sb.append(" on lock=" + ti.getLockName() + "\n"); } if (ti.isSuspended()) { sb.append(" (suspended)" + "\n"); } if (ti.isInNative()) { sb.append(" (running in native)" + "\n"); } if (ti.getLockOwnerName() != null) { sb.append(INDENT + " owned by " + ti.getLockOwnerName() + " Id=" + ti.getLockOwnerId() + "\n"); } }
From source file:DeadLockDetector.java
/** * Check if there is a DeadLock.//from w ww .ja v a2 s.com */ @Override public final void run() { boolean deadlock = false; while (!deadlock) { try { long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { /** deadlock found :/ */ deadlock = true; ThreadInfo[] tis = tmx.getThreadInfo(ids, true, true); String info = "DeadLock Found!\n"; for (ThreadInfo ti : tis) { info += ti.toString(); } for (ThreadInfo ti : tis) { LockInfo[] locks = ti.getLockedSynchronizers(); MonitorInfo[] monitors = ti.getLockedMonitors(); if (locks.length == 0 && monitors.length == 0) { /** this thread is deadlocked but its not guilty */ continue; } ThreadInfo dl = ti; info += "Java-level deadlock:\n"; info += "\t" + dl.getThreadName() + " is waiting to lock " + dl.getLockInfo().toString() + " which is held by " + dl.getLockOwnerName() + "\n"; while ((dl = tmx.getThreadInfo(new long[] { dl.getLockOwnerId() }, true, true)[0]) .getThreadId() != ti.getThreadId()) { info += "\t" + dl.getThreadName() + " is waiting to lock " + dl.getLockInfo().toString() + " which is held by " + dl.getLockOwnerName() + "\n"; } } System.out.println(info); if (doWhenDL == RESTART) { System.exit(0); } } Thread.sleep(sleepTime); } catch (Exception e) { System.out.println(e); } } }
From source file:org.opendaylight.controller.config.threadpool.fixed.FixedThreadPoolConfigBeanTest.java
private int countThreadsByPrefix(String prefix) { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); int result = 0; List<String> names = new ArrayList<>(); for (ThreadInfo threadInfo : threadMXBean.dumpAllThreads(false, false)) { names.add(threadInfo.getThreadName()); if (threadInfo.getThreadName().startsWith(prefix)) { result++;/* www . j a v a 2 s .c o m*/ } } LOG.info("Current threads {}", names); return result; }
From source file:serposcope.controllers.admin.AdminController.java
public Result stackdump(Context context) { return Results.contentType("text/plain").render((ctx, res) -> { ResponseStreams responseStreams = context.finalizeHeaders(res); try (PrintWriter writer = new PrintWriter(responseStreams.getOutputStream());) { final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (ThreadInfo threadInfo : threadInfos) { writer.append('"'); writer.append(threadInfo.getThreadName()); writer.append("\" "); final Thread.State state = threadInfo.getThreadState(); writer.append("\n java.lang.Thread.State: "); writer.append(state.toString()); final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); for (final StackTraceElement stackTraceElement : stackTraceElements) { writer.append("\n at "); writer.append(stackTraceElement.toString()); }/*w w w.j ava2 s . c om*/ writer.println("\n"); } } catch (IOException ex) { LOG.error("stackdump", ex); } }); }
From source file:models.monitor.MonitorProvider.java
public ThreadUsage getThreadUsage() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); ThreadUsage threadUsage = new ThreadUsage(); long[] threadIds = threadMxBean.getAllThreadIds(); threadUsage.liveThreadCount = threadIds.length; for (long tId : threadIds) { ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId); threadUsage.threadData.put(new Long(tId).toString(), new ThreadData(threadInfo.getThreadName(), threadInfo.getThreadState().name(), threadMxBean.getThreadCpuTime(tId))); }//from w ww .j a va 2 s . c o m return threadUsage; }
From source file:morphy.service.ThreadService.java
/** * Dumps stack traces of all threads to threaddump.txt. *///w w w. j ava 2 s.com public void threadDump() { LOG.error("All threads are in use. Logging the thread stack trace to threaddump.txt and exiting."); final ThreadMXBean threads = ManagementFactory.getThreadMXBean(); long[] threadIds = threads.getAllThreadIds(); PrintWriter printWriter = null; try { printWriter = new PrintWriter(new FileWriter(THREAD_DUMP_FILE_PATH, false)); printWriter.println("Morphy ThreadService initiated dump " + new Date()); for (long threadId : threadIds) { ThreadInfo threadInfo = threads.getThreadInfo(threadId, 10); printWriter.println("Thread " + threadInfo.getThreadName() + " Block time:" + threadInfo.getBlockedTime() + " Block count:" + threadInfo.getBlockedCount() + " Lock name:" + threadInfo.getLockName() + " Waited Count:" + threadInfo.getWaitedCount() + " Waited Time:" + threadInfo.getWaitedTime() + " Is Suspended:" + threadInfo.isSuspended()); StackTraceElement[] stackTrace = threadInfo.getStackTrace(); for (StackTraceElement element : stackTrace) { printWriter.println(element); } } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (printWriter != null) { try { printWriter.flush(); printWriter.close(); } catch (Exception e2) { } } } }
From source file:hudson.Functions.java
@IgnoreJRERequirement public static String dumpThreadInfo(ThreadInfo ti) { StringBuilder sb = new StringBuilder( "\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " " + ti.getThreadState()); if (ti.getLockName() != null) { sb.append(" on " + ti.getLockName()); }/*from www . j a v a 2s.c o m*/ if (ti.getLockOwnerName() != null) { sb.append(" owned by \"" + ti.getLockOwnerName() + "\" Id=" + ti.getLockOwnerId()); } if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); StackTraceElement[] stackTrace = ti.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat " + ste.toString()); sb.append('\n'); if (i == 0 && ti.getLockInfo() != null) { Thread.State ts = ti.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on " + ti.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked " + mi); sb.append('\n'); } } } LockInfo[] locks = ti.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); }