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: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.ja v 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("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:org.apache.flink.runtime.metrics.util.MetricUtils.java

private static void instantiateThreadMetrics(MetricGroup metrics) {
    final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

    metrics.gauge("Count", new Gauge<Integer>() {
        @Override/*w w  w . j a v  a  2 s  . co  m*/
        public Integer getValue() {
            return mxBean.getThreadCount();
        }
    });
}

From source file:madgik.exareme.worker.art.container.dataTrasferMgr.DataTransferMgr.java

@Override
public void addSuccesfulTransfer(Integer DtRegId) throws Exception {
    log.trace("addSuccesfulTransfer: " + DtRegId);
    if (RedIdToTransferId.containsKey(DtRegId)) {
        int DtOpId = RedIdToTransferId.get(DtRegId);
        RedIdToTransferId.remove(DtRegId);
        transferIdToRegIds.get(DtOpId).remove(DtRegId);
        transferIDToNumOfDts.put(DtOpId, transferIDToNumOfDts.get(DtOpId) - 1);

        if (transferIDToNumOfDts.get(DtOpId) == 0) {

            AbstractOperatorImpl aoimp = transferIdToAoimpl.get(DtOpId);

            aoimp.exit(0);//w ww  .  j a v  a  2s  .  c om
            aoimp.finalizeOperator();

            long end = System.currentTimeMillis();
            aoimp.getSessionManager().getOperatorStatistics().setEndTime_ms(end);
            aoimp.getSessionManager().getOperatorStatistics().setExitCode(aoimp.getExitCode());
            aoimp.getSessionManager().getOperatorStatistics().setExitMessage(aoimp.getExitMessage());

            aoimp.getSessionManager().getOperatorStatistics().setTotalTime_ms(end - aoimp.start,
                    ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime() / 1000000);

            log.trace("addSuccesfulTransfer done all");
            aoimp.getSessionManager().getSessionReportID().reportManagerProxy.operatorSuccess(
                    aoimp.getSessionManager().getOpID(), aoimp.getExitCode(), aoimp.getExitMessage(),
                    new Date(), aoimp.getSessionManager().getContainerID(), true);
            aoimp.freeresources(aoimp.getSessionManager().getOpID());
            transferIdToAoimpl.remove(DtOpId);

            transferIDToNumOfDts.remove(DtOpId);

        }
        RegIDToFilename.remove(DtRegId);
        RegIDToTableFile.remove(DtRegId);
        RedIdToTransferId.remove(DtRegId);
    }
}

From source file:org.cloudfoundry.identity.statsd.UaaMetricsEmitter.java

@Scheduled(fixedRate = 5000, initialDelay = 3000)
public void emitJvmVitals() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    String prefix = "vitals.jvm.";
    invokeIfPresent(prefix + "cpu.load", osBean, "getProcessCpuLoad", d -> (long) (d.doubleValue() * 100));
    statsDClient.gauge(prefix + "thread.count", threadBean.getThreadCount());
    Map<String, MemoryUsage> memory = new HashMap<>();
    memory.put("heap", memoryBean.getHeapMemoryUsage());
    memory.put("non-heap", memoryBean.getNonHeapMemoryUsage());
    memory.entrySet().stream().forEach(m -> {
        statsDClient.gauge(prefix + m.getKey() + ".init", m.getValue().getInit());
        statsDClient.gauge(prefix + m.getKey() + ".committed", m.getValue().getCommitted());
        statsDClient.gauge(prefix + m.getKey() + ".used", m.getValue().getUsed());
        statsDClient.gauge(prefix + m.getKey() + ".max", m.getValue().getMax());
    });//from   ww  w  . ja  v  a 2  s .c om

}

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/* ww w .j  a  va  2s  . c o  m*/

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

From source file:fr.gael.dhus.server.http.valve.processings.ProcessingValve.java

private ThreadMXBean getThreadMxBean() {
    if (ProcessingValve.threadMxBean == null) {
        ThreadMXBean tmxBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
        if (!tmxBean.isCurrentThreadCpuTimeSupported()) {
            throw new UnsupportedOperationException("Thread CPU monitoring not supported.");
        }//from   w  w  w  .  j a v a 2 s.co  m
        if (tmxBean.isThreadCpuTimeSupported() && !tmxBean.isThreadCpuTimeEnabled()) {
            tmxBean.setThreadCpuTimeEnabled(true);
        }
        if (tmxBean.isThreadAllocatedMemorySupported() && !tmxBean.isThreadAllocatedMemoryEnabled()) {
            tmxBean.setThreadAllocatedMemoryEnabled(true);
        }

        ProcessingValve.threadMxBean = tmxBean;
    }
    return ProcessingValve.threadMxBean;
}

From source file:com.microsoft.sqlserver.jdbc.connection.PoolingTest.java

/**
 * count number of mssql-jdbc-TimeoutTimer threads
 * /*from w  w w.  j av  a 2  s  . c om*/
 * @return
 */
private static int countTimeoutThreads() {
    int count = 0;
    String threadName = "mssql-jdbc-TimeoutTimer";

    ThreadInfo[] tinfos = ManagementFactory.getThreadMXBean()
            .getThreadInfo(ManagementFactory.getThreadMXBean().getAllThreadIds(), 0);

    for (ThreadInfo ti : tinfos) {
        if ((ti.getThreadName().startsWith(threadName))
                && (ti.getThreadState().equals(java.lang.Thread.State.TIMED_WAITING))) {
            count++;
        }
    }

    return count;
}

From source file:org.apache.hyracks.control.nc.NodeControllerService.java

public NodeControllerService(NCConfig ncConfig) throws Exception {
    this.ncConfig = ncConfig;
    id = ncConfig.nodeId;//  w  ww. j  a v a 2s . c  o  m
    ipc = new IPCSystem(new InetSocketAddress(ncConfig.clusterNetIPAddress, ncConfig.clusterNetPort),
            new NodeControllerIPCI(this), new CCNCFunctions.SerializerDeserializer());

    ioManager = new IOManager(getDevices(ncConfig.ioDevices));
    if (id == null) {
        throw new Exception("id not set");
    }
    partitionManager = new PartitionManager(this);
    netManager = new NetworkManager(ncConfig.dataIPAddress, ncConfig.dataPort, partitionManager,
            ncConfig.nNetThreads, ncConfig.nNetBuffers, ncConfig.dataPublicIPAddress, ncConfig.dataPublicPort,
            FullFrameChannelInterfaceFactory.INSTANCE);

    lccm = new LifeCycleComponentManager();
    workQueue = new WorkQueue(id, Thread.NORM_PRIORITY); // Reserves MAX_PRIORITY of the heartbeat thread.
    jobletMap = new Hashtable<>();
    timer = new Timer(true);
    serverCtx = new ServerContext(ServerContext.ServerType.NODE_CONTROLLER,
            new File(new File(NodeControllerService.class.getName()), id));
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    threadMXBean = ManagementFactory.getThreadMXBean();
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    osMXBean = ManagementFactory.getOperatingSystemMXBean();
    registrationPending = true;
    getNodeControllerInfosAcceptor = new MutableObject<>();
    memoryManager = new MemoryManager(
            (long) (memoryMXBean.getHeapMemoryUsage().getMax() * MEMORY_FUDGE_FACTOR));
    ioCounter = new IOCounterFactory().getIOCounter();
}

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);/*from  w  w w . j av a  2 s .com*/
    }

    //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:edu.uci.ics.hyracks.control.nc.NodeControllerService.java

public NodeControllerService(NCConfig ncConfig) throws Exception {
    this.ncConfig = ncConfig;
    id = ncConfig.nodeId;//from ww  w.j a  v  a  2s .  com
    NodeControllerIPCI ipci = new NodeControllerIPCI();
    ipc = new IPCSystem(new InetSocketAddress(ncConfig.clusterNetIPAddress, ncConfig.clusterNetPort), ipci,
            new CCNCFunctions.SerializerDeserializer());

    this.ctx = new RootHyracksContext(this, new IOManager(getDevices(ncConfig.ioDevices)));
    if (id == null) {
        throw new Exception("id not set");
    }
    partitionManager = new PartitionManager(this);
    netManager = new NetworkManager(ncConfig.dataIPAddress, ncConfig.dataPort, partitionManager,
            ncConfig.nNetThreads, ncConfig.nNetBuffers, ncConfig.dataPublicIPAddress, ncConfig.dataPublicPort);

    lccm = new LifeCycleComponentManager();
    queue = new WorkQueue();
    jobletMap = new Hashtable<JobId, Joblet>();
    timer = new Timer(true);
    serverCtx = new ServerContext(ServerContext.ServerType.NODE_CONTROLLER,
            new File(new File(NodeControllerService.class.getName()), id));
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    threadMXBean = ManagementFactory.getThreadMXBean();
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    osMXBean = ManagementFactory.getOperatingSystemMXBean();
    registrationPending = true;
    getNodeControllerInfosAcceptor = new MutableObject<FutureValue<Map<String, NodeControllerInfo>>>();
    memoryManager = new MemoryManager(
            (long) (memoryMXBean.getHeapMemoryUsage().getMax() * MEMORY_FUDGE_FACTOR));
    ioCounter = new IOCounterFactory().getIOCounter();
}