Example usage for java.lang.management ManagementFactory getThreadMXBean

List of usage examples for java.lang.management ManagementFactory getThreadMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getThreadMXBean.

Prototype

public static ThreadMXBean getThreadMXBean() 

Source Link

Document

Returns the managed bean for the thread system of the Java virtual machine.

Usage

From source file:net.bull.javamelody.internal.model.JavaInformations.java

public JavaInformations(ServletContext servletContext, boolean includeDetails) {
    // CHECKSTYLE:ON
    super();/*w ww .  j a va  2s.c  o  m*/
    memoryInformations = new MemoryInformations();
    tomcatInformationsList = TomcatInformations.buildTomcatInformationsList();
    sessionCount = SessionListener.getSessionCount();
    sessionAgeSum = SessionListener.getSessionAgeSum();
    activeThreadCount = JdbcWrapper.getActiveThreadCount();
    usedConnectionCount = JdbcWrapper.getUsedConnectionCount();
    activeConnectionCount = JdbcWrapper.getActiveConnectionCount();
    maxConnectionCount = JdbcWrapper.getMaxConnectionCount();
    transactionCount = JdbcWrapper.getTransactionCount();
    systemLoadAverage = buildSystemLoadAverage();
    systemCpuLoad = buildSystemCpuLoad();
    processCpuTimeMillis = buildProcessCpuTimeMillis();
    unixOpenFileDescriptorCount = buildOpenFileDescriptorCount();
    unixMaxFileDescriptorCount = buildMaxFileDescriptorCount();
    host = Parameters.getHostName() + '@' + Parameters.getHostAddress();
    os = buildOS();
    availableProcessors = Runtime.getRuntime().availableProcessors();
    javaVersion = System.getProperty("java.runtime.name") + ", " + System.getProperty("java.runtime.version");
    jvmVersion = System.getProperty("java.vm.name") + ", " + System.getProperty("java.vm.version") + ", "
            + System.getProperty("java.vm.info");
    if (servletContext == null) {
        serverInfo = null;
        contextPath = null;
        contextDisplayName = null;
        webappVersion = null;
    } else {
        serverInfo = servletContext.getServerInfo();
        contextPath = Parameters.getContextPath(servletContext);
        contextDisplayName = servletContext.getServletContextName();
        webappVersion = MavenArtifact.getWebappVersion();
    }
    startDate = START_DATE;
    jvmArguments = buildJvmArguments();
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    threadCount = threadBean.getThreadCount();
    peakThreadCount = threadBean.getPeakThreadCount();
    totalStartedThreadCount = threadBean.getTotalStartedThreadCount();
    freeDiskSpaceInTemp = Parameters.TEMPORARY_DIRECTORY.getFreeSpace();
    springBeanExists = SPRING_AVAILABLE && SpringContext.getSingleton() != null;

    if (includeDetails) {
        dataBaseVersion = buildDataBaseVersion();
        dataSourceDetails = buildDataSourceDetails();
        threadInformationsList = buildThreadInformationsList();
        cacheInformationsList = CacheInformations.buildCacheInformationsList();
        jobInformationsList = JobInformations.buildJobInformationsList();
        pid = PID.getPID();
    } else {
        dataBaseVersion = null;
        dataSourceDetails = null;
        threadInformationsList = null;
        cacheInformationsList = null;
        jobInformationsList = null;
        pid = null;
    }
}

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();//w  w w .j a va2  s.  c om

    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:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin/* w w  w .j a  va2 s  . c om*/
@APIDescription("Gets the application system thread and status")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(ThreadStatus.class)
@Path("/threads")
public List<ThreadStatus> getThreads() {
    List<ThreadStatus> threadStatuses = new ArrayList<>();

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo threadInfos[] = threadMXBean.dumpAllThreads(false, false);

    for (ThreadInfo info : threadInfos) {
        ThreadStatus threadStatus = new ThreadStatus();
        threadStatus.setId(info.getThreadId());
        threadStatus.setName(info.getThreadName());
        threadStatus.setStatus(info.getThreadState().name());
        threadStatus
                .setDetails(info.toString().replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").replace("\n", "<br>"));
        threadStatuses.add(threadStatus);
    }

    return threadStatuses;
}

From source file:org.jitsi.meet.test.FailureListener.java

/**
 * Saves current java thread dump./*  w  w w .  j a v  a  2  s .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.jitsi.meet.test.base.FailureListener.java

/**
 * Saves current java thread dump./*from w  w  w.  j  a  va2  s .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) {
        e.printStackTrace();
    }
}

From source file:com.alibaba.druid.benckmark.pool.Case4.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    final TableOperator operator = new TableOperator();
    operator.setDataSource(dataSource);/* w w w.jav a2 s  .  c o  m*/
    operator.createTable();
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        operator.insert();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();
    operator.dropTable();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount));

}

From source file:EventDispatchThreadHangMonitor.java

private static void checkForDeadlock() {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long[] threadIds = threadBean.findMonitorDeadlockedThreads();
    if (threadIds == null) {
        return;/*w  ww .  j  a v  a2 s. com*/
    }
    Log.warn("deadlock detected involving the following threads:");
    ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
    for (ThreadInfo info : threadInfos) {
        Log.warn("Thread #" + info.getThreadId() + " " + info.getThreadName() + " (" + info.getThreadState()
                + ") waiting on " + info.getLockName() + " held by " + info.getLockOwnerName()
                + stackTraceToString(info.getStackTrace()));
    }
}

From source file:jtabwb.launcher.Launcher.java

/**
 * Constructs a new launcher.//from   w ww. j a  v  a 2 s  .c  o  m
 */
public Launcher() {
    this.LOG = new Log();
    this.processCmdLineOptionsExecuted = false;
    this.currentConfiguration = new LaunchConfiguration();
    bean = ManagementFactory.getThreadMXBean();
}

From source file:org.renjin.primitives.System.java

/**
 * Returns object of class "proc_time" which is a numeric vector of
 * length 5, containing the user, system, and total elapsed times for
 * the currently running R process, and the cumulative sum of user
 * and system times of any child processes spawned by it on which it
 * has waited. //from  w w w.j  a v  a  2s  .c  o m
 *
 * _The user time is the CPU time charged for the execution of user
 *  instructions of the calling process. The system time is the CPU
 *  time charged for execution by the system on behalf of the calling
 *  process._
 */
@Builtin("proc.time")
public static DoubleVector procTime() {

    DoubleArrayVector.Builder result = new DoubleArrayVector.Builder();
    StringVector.Builder names = new StringVector.Builder();

    long totalCPUTime;
    long userCPUTime;
    long elapsedTime;

    // There doesn't seem to be any platform-independent way of accessing
    // CPU use for the whole JVM process, so we'll have to make do
    // with the timings for the thread we're running on.
    //
    // Additionally, the MX Beans may not be available in all environments,
    // so we need to fallback to app
    try {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        totalCPUTime = threadMXBean.getCurrentThreadCpuTime();
        userCPUTime = threadMXBean.getCurrentThreadUserTime();

        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        elapsedTime = runtimeMXBean.getUptime();
    } catch (Error e) {
        // ThreadMXBean is not available in all environments
        // Specifically, AppEngine will throw variously SecurityErrors or
        // ClassNotFoundErrors if we try to access these classes
        userCPUTime = totalCPUTime = java.lang.System.nanoTime();
        elapsedTime = new Date().getTime();
    }

    // user.self
    names.add("user.self");
    result.add(userCPUTime / NANOSECONDS_PER_SECOND);

    // sys.self
    names.add("sys.self");
    result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND);

    // elapsed
    // (wall clock time)
    names.add("elapsed");
    result.add(elapsedTime / MILLISECONDS_PER_SECOND);

    // AFAIK, we don't have any platform independent way of accessing
    // this info.

    // user.child
    names.add("user.child");
    result.add(0);

    // sys.child
    names.add("sys.child");
    result.add(0);

    result.setAttribute(Symbols.NAMES, names.build());
    result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time"));
    return result.build();

}