Example usage for java.lang.management ThreadMXBean getThreadCpuTime

List of usage examples for java.lang.management ThreadMXBean getThreadCpuTime

Introduction

In this page you can find the example usage for java.lang.management ThreadMXBean getThreadCpuTime.

Prototype

public long getThreadCpuTime(long id);

Source Link

Document

Returns the total CPU time for a thread of the specified ID in nanoseconds.

Usage

From source file:ThreadTimer.java

public static long getThreadTime(long tid) {
    ThreadMXBean tb = ManagementFactory.getThreadMXBean();
    return tb.getThreadCpuTime(tid);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);// ww  w . j  a  v a 2s .  c o m
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_MultiThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(10, 10, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);//from  w  ww.ja  v  a 2s  .  c om
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Multithreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Multithreaded overall usage: " + actualUsage);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void cpuUsageRoughlyAdheredTo_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();

    float expectedCpuUsage = MAX_USAGE;

    BatchCpuThrottlingExecutor e = getExecutor(1, expectedCpuUsage, factory);

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);/*from  w  w w.j  a va  2s  .  co  m*/
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("Singlethreaded overall usage: " + actualUsage);

    //this CPU throttling stuff might not be too precise, so let's fail only on huge difference.
    float min = expectedCpuUsage * .5f;
    float max = expectedCpuUsage * 1.5f;

    Assert.assertTrue(min < actualUsage && actualUsage < max, "Actual CPU usage out of expected range: (" + min
            + ", " + expectedCpuUsage + ", " + max + ") != " + actualUsage);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void cpuUsageRoughlyAdheredTo_MultiThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();

    float expectedCpuUsage = MAX_USAGE;

    BatchCpuThrottlingExecutor e = getExecutor(10, expectedCpuUsage, factory);

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);//ww  w .  j  av a 2  s  .c  o  m
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("Multithreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("Multithreaded overall usage: " + actualUsage);

    //this CPU throttling stuff might not be too precise, so let's fail only on huge difference.
    float min = expectedCpuUsage * .5f;
    float max = expectedCpuUsage * 1.5f;

    Assert.assertTrue(min < actualUsage && actualUsage < max, "Actual CPU usage out of expected range: (" + min
            + ", " + expectedCpuUsage + ", " + max + ") != " + actualUsage);
}

From source file:com.streamsets.datacollector.restapi.AdminResource.java

@GET
@Path("/threads")
@ApiOperation(value = "Returns Thread Dump along with stack trace", response = Map.class, responseContainer = "List", authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)//from  www . j  a  va2  s .c  o m
@RolesAllowed({ AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE })
public Response getThreadsDump() throws IOException {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);
    List<Map> augmented = new ArrayList<>(threads.length);
    for (ThreadInfo thread : threads) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("threadInfo", thread);
        map.put("userTimeNanosecs", threadMXBean.getThreadUserTime(thread.getThreadId()));
        map.put("cpuTimeNanosecs", threadMXBean.getThreadCpuTime(thread.getThreadId()));
        augmented.add(map);
    }
    return Response.ok(augmented).build();
}

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)));

    }/*ww  w .  j  av  a2 s  .co m*/
    return threadUsage;
}

From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

public MagicCommandOutput time(String codeToExecute, Message message, int executionCount, boolean showResult) {
    CompletableFuture<TimeMeasureData> compileTime = new CompletableFuture<>();

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    long currentThreadId = Thread.currentThread().getId();

    Long startWallTime = System.nanoTime();
    Long startCpuTotalTime = threadMXBean.getCurrentThreadCpuTime();
    Long startUserTime = threadMXBean.getCurrentThreadUserTime();

    SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel, message,
            executionCount);/*from   www  .j  a va  2s  . c o m*/
    if (!showResult) {
        simpleEvaluationObject.noResult();
    }

    TryResult either = kernel.executeCode(codeToExecute, simpleEvaluationObject);

    Long endWallTime = System.nanoTime();
    Long endCpuTotalTime = threadMXBean.getThreadCpuTime(currentThreadId);
    Long endUserTime = threadMXBean.getThreadUserTime(currentThreadId);

    compileTime.complete(new TimeMeasureData(endCpuTotalTime - startCpuTotalTime, endUserTime - startUserTime,
            endWallTime - startWallTime));
    String messageInfo = "CPU times: user %s, sys: %s, total: %s \nWall Time: %s\n";

    try {
        TimeMeasureData timeMeasuredData = compileTime.get();

        return new MagicCommandOutput(MagicCommandOutput.Status.OK,
                String.format(messageInfo, format(timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime() - timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime()), format(timeMeasuredData.getWallTime())),
                either, simpleEvaluationObject);

    } catch (InterruptedException | ExecutionException e) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "There occurs problem during measuring time for your statement.");
    }
}

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

public static List<ThreadInformations> buildThreadInformationsList() {
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    final List<Thread> threads = new ArrayList<Thread>(stackTraces.keySet());

    // si "1.6.0_01".compareTo(Parameters.JAVA_VERSION) > 0;
    // on rcuprait les threads sans stack trace en contournant bug 6434648 avant 1.6.0_01
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
    // hormis pour le thread courant qui obtient sa stack trace diffremment sans le bug
    //      threads = getThreadsFromThreadGroups();
    //      final Thread currentThread = Thread.currentThread();
    //      stackTraces = Collections.singletonMap(currentThread, currentThread.getStackTrace());

    final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported() && threadBean.isThreadCpuTimeEnabled();
    final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
    final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(threads.size());
    // hostAddress rcupr ici car il peut y avoir plus de 20000 threads
    final String hostAddress = Parameters.getHostAddress();
    for (final Thread thread : threads) {
        final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
        final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
                : new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
        final long cpuTimeMillis;
        final long userTimeMillis;
        if (cpuTimeEnabled) {
            cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
            userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
        } else {//from   w  ww.j  a  va  2s.  co  m
            cpuTimeMillis = -1;
            userTimeMillis = -1;
        }
        final boolean deadlocked = deadlockedThreads != null
                && Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
        // stackTraceElementList est une ArrayList et non unmodifiableList pour lisibilit xml
        threadInfosList.add(new ThreadInformations(thread, stackTraceElementList, cpuTimeMillis, userTimeMillis,
                deadlocked, hostAddress));
    }
    // on retourne ArrayList et non unmodifiableList pour lisibilit du xml par xstream
    return threadInfosList;
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void measureTimes(ArrayList<Runnable> profilingQueue) {
    try {//from   w  w w .j  av a 2  s.  c  o m
        this.element = new TimeElement("");

        // get the MXBean
        final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

        // wait till the warm up period is over
        while (!this.running) {
            try {
                Thread.sleep(1);
            } catch (final InterruptedException e) {
            }
        }

        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
        }

        // initialize the start times of the threads
        for (int i = 0; i < this.threadIds.length; i++) {
            this.currentThreadTimes[i] = mxBean.getThreadCpuTime(this.threadIds[i]);
        }

        BenchmarkTest.LOG.info("Sampling interval: {0} millisec(s)", BenchmarkTest.SAMPLING_INT);

        long lastTime = System.currentTimeMillis();

        // profile until the benchmark is over
        while (BenchmarkTest.this.running) {
            try {
                final long now = System.currentTimeMillis();
                final long diff = Math.abs(now - lastTime);
                if (diff > BenchmarkTest.SAMPLING_INT) {
                    this.measureTimes(mxBean, profilingQueue);

                    lastTime = now;
                } else {
                    Thread.sleep(1);
                }
            } catch (final InterruptedException e) {
            }
        }

        this.samplingFinished = true;
    } catch (final Exception e) {
        BenchmarkTest.LOG.fatal(e, "");
    }
}