Java Code Examples for java.lang.management.ThreadMXBean

The following are top voted examples for showing how to use java.lang.management.ThreadMXBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: MantaroRPG   File: AsyncInfoMonitor.java   Source Code and License 7 votes vote down vote up
public static void start() {
	if (started) throw new IllegalStateException("Already Started.");
	OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
	ThreadMXBean thread = ManagementFactory.getThreadMXBean();
	Runtime r = Runtime.getRuntime();
	int mb = 0x100000;

	lastSystemTime = System.nanoTime();
	lastProcessCpuTime = calculateProcessCpuTime(os);

	Async.task("AsyncInfoMonitorThread", () -> {
		threadCount = thread.getThreadCount();
		availableProcessors = r.availableProcessors();
		freeMemory = Runtime.getRuntime().freeMemory() / mb;
		maxMemory = Runtime.getRuntime().maxMemory() / mb;
		totalMemory = Runtime.getRuntime().totalMemory() / mb;
		cpuUsage = calculateCpuUsage(os);
		vpsCPUUsage = getVpsCPUUsage(os);
		vpsFreeMemory = calculateVPSFreeMemory(os);
		vpsMaxMemory = calculateVPSMaxMemory(os);
		vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
	}, 1);
	started = true;
}
 
Example 2
Project: angel   File: ExecutorsBlock.java   Source Code and License 6 votes vote down vote up
@Override
protected void render(Block html) {
  set(TITLE, join("Angel ExecutorsBlock"));
  TBODY<TABLE<Hamlet>> tbody =
      html.h1("ExecutorsBlock").table("#jobs").thead().tr().th(_TH, "id").th(_TH, "name")
          .th(_TH, "state").th(_TH, "stacktrace")._()._().tbody();

  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(true, true);
  StringBuilder stackTraceString;
  for (ThreadInfo t : threadInfo) {
    stackTraceString = new StringBuilder();
    StackTraceElement[] stackTrace = t.getStackTrace();
    for (StackTraceElement s : stackTrace) {
      stackTraceString.append(s.toString()).append("\n");
    }
    tbody.tr().td(String.valueOf(t.getThreadId())).td(String.valueOf(t.getThreadName()))
        .td(String.valueOf(t.getThreadState())).td(String.valueOf(stackTraceString.toString()))._();
  }
  tbody._()._();


}
 
Example 3
Project: angel   File: ParameterServerService.java   Source Code and License 6 votes vote down vote up
/**
 * Gets thread stack.
 *
 * @return the thread stack
 */
private String getThreadStack()
{
  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  ThreadInfo[] threadInfo =  threadMXBean.dumpAllThreads(true, true);
  StringBuilder stackTraceString= new StringBuilder("ParameterServer\n");
  StringBuilder infoBlock= new StringBuilder("\n");
  for(ThreadInfo t :  threadInfo)
  {
    infoBlock = new StringBuilder("\n\n");
    infoBlock.append("threadid: ").append(t.getThreadId()).append(" threadname: ").append(t.getThreadName()).append("       threadstate: ").append(t.getThreadState()).append("\n");
    for(StackTraceElement stackTraceElement : t.getStackTrace())
    {
      infoBlock.append("   ").append(stackTraceElement.toString()).append("\n");
    }
    stackTraceString.append(infoBlock).append("\n\n");
  }
  return stackTraceString.toString();
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: MetricsServoRegistry.java   Source Code and License 6 votes vote down vote up
@Override
public String call() {
  Map<String, String> memoryMap = new HashMap<>();
  OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
  double cpu = osMxBean.getSystemLoadAverage();
  memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces)));

  ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean();
  int threadCount = threadmxBean.getThreadCount();
  memoryMap.put("cpuRunningThreads", String.valueOf(threadCount));

  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit()));
  memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax()));
  memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted()));
  memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed()));
  memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit()));
  memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax()));
  memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted()));
  memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed()));
  return memoryMap.toString();
}
 
Example 5
Project: swage   File: ThreadSensor.java   Source Code and License 6 votes vote down vote up
@Override
public void sense(final MetricRecorder.Context metricContext)
{
    ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

    int current = mxBean.getThreadCount();
    int peak = mxBean.getPeakThreadCount();

    if (peak > historicalPeak) {
        historicalPeak = peak;
    }

    metricContext.record(THREADS, current, Unit.NONE);
    metricContext.record(PERIODIC_PEAK_THREADS, peak, Unit.NONE);
    metricContext.record(PEAK_THREADS, historicalPeak, Unit.NONE);

    mxBean.resetPeakThreadCount();
}
 
Example 6
Project: incubator-netbeans   File: StackTraceSnapshotBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReset() {
    System.out.println("reset");
    ThreadMXBean tbean = ManagementFactory.getThreadMXBean();
    addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime());
    addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime());

    instance.reset();
    assertTrue(instance.methodInfos.size()-1 == 0);
    assertTrue(instance.threadIds.size() == 0);
    assertTrue(instance.threadNames.size() == 0);
    assertEquals(-1L, instance.currentDumpTimeStamp);
    //assertEquals(-1L, instance.firstDumpTimeStamp);
    assertEquals(0, instance.stackTraceCount);

    try {
        instance.createSnapshot(System.currentTimeMillis());
        fail();
    } catch (CPUResultsSnapshot.NoDataAvailableException ex) {
    }
}
 
Example 7
Project: hadoop-oss   File: TestShell.java   Source Code and License 6 votes vote down vote up
private static int countTimerThreads() {
  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("Timer")) {
        count++;
        break;
      }
    }
  }
  return count;
}
 
Example 8
Project: hadoop-oss   File: TimedOutTestsListener.java   Source Code and License 6 votes vote down vote up
static String buildDeadlockInfo() {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  long[] threadIds = threadBean.findMonitorDeadlockedThreads();
  if (threadIds != null && threadIds.length > 0) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter out = new PrintWriter(stringWriter);
    
    ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
    for (ThreadInfo ti : infos) {
      printThreadInfo(ti, out);
      printLockInfo(ti.getLockedSynchronizers(), out);
      out.println();
    }
    
    out.close();
    return stringWriter.toString();
  } else {
    return null;
  }
}
 
Example 9
Project: hadoop-oss   File: TestRpcBase.java   Source Code and License 6 votes vote down vote up
/**
 * Count the number of threads that have a stack frame containing
 * the given string
 */
protected 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;
}
 
Example 10
Project: cornerstone   File: ThreadingManager.java   Source Code and License 6 votes vote down vote up
public static List<TInfo> getAllThreadInfo(){

        List<TInfo> threads = new ArrayList<>();
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        long[] ids = threadBean.getAllThreadIds();
        ThreadInfo[] infos = threadBean.getThreadInfo(ids);
        for (ThreadInfo info : infos){
            long id = info.getThreadId();
            TInfo tInfo = new TInfo();
            tInfo.name = info.getThreadName();
            tInfo.id = id;
            tInfo.state = info.getThreadState();
            tInfo.cpuTime = threadBean.getThreadCpuTime(id);
            threads.add(tInfo);
        }
        Collections.sort(threads,new Comparator<TInfo>() {
            @Override
            public int compare(TInfo o1, TInfo o2) {
                return Long.compare(o2.cpuTime,o1.cpuTime);
            }
        });
        return threads;
    }
 
Example 11
Project: cornerstone   File: ThreadingManager.java   Source Code and License 6 votes vote down vote up
public static ThreadInfo[] dump(int maxDepth,boolean onlyDeadLock){
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    long[] ids ;
    if(onlyDeadLock) {
        ids = threadBean.findDeadlockedThreads();
    }else {
       ids = threadBean.getAllThreadIds();
    }
    if(ids !=null) {
        return threadBean.getThreadInfo(ids, maxDepth);
    }
    else {
        return null;
    }


}
 
Example 12
Project: micrometer   File: JvmThreadMetrics.java   Source Code and License 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount)
        .tags(tags)
        .description("The peak live thread count since the Java virtual machine started or peak was reset")
        .register(registry);

    Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount)
        .tags(tags)
        .description("The current number of live daemon threads")
        .register(registry);

    Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount)
        .tags(tags)
        .description("The current number of live threads including both daemon and non-daemon threads")
        .register(registry);
}
 
Example 13
Project: ats-framework   File: ThreadUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @return Set of the IDs of all threads that are started except the "main" thread.
 */
public Set<Long> getAllThreadIDsExceptMain() {

    ThreadMXBean thbean = ManagementFactory.getThreadMXBean();
    // get the IDs of all live threads.
    long[] threadIDs = thbean.getAllThreadIds();
    Set<Long> res = new HashSet<Long>();

    // get the IDs of all threads except main
    for (long id : threadIDs) {
        Thread t = getThread(id);
        if (t != null && !"main".equals(t.getName())) {
            res.add(id);
        }
    }

    return res;
}
 
Example 14
Project: ats-framework   File: ThreadUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @return a list of all threads started in the JVM.
 */
public List<Thread> getAllThreads() {

    final ThreadGroup root = getRootThreadGroup();
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean();
    // get the number of all live threads
    int nAlloc = thbean.getThreadCount();
    int n = 0;
    Thread[] threads;

    do {
        nAlloc *= 2; // increase the size since more threads may have been created
        threads = new Thread[nAlloc];
        n = root.enumerate(threads, true); // get all active threads from this thread group
    } while (n == nAlloc); // stop if all active threads are enumerated

    List<Thread> res = new ArrayList<Thread>();
    for (Thread th : threads) {
        res.add(th);
    }

    return res;
}
 
Example 15
Project: GabrielBot   File: AsyncInfoMonitor.java   Source Code and License 6 votes vote down vote up
public static void start() {
    if (started) throw new IllegalStateException("Already Started.");
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean thread = ManagementFactory.getThreadMXBean();
    Runtime r = Runtime.getRuntime();
    int mb = 0x100000;

    lastSystemTime = System.nanoTime();
    lastProcessCpuTime = calculateProcessCpuTime(os);

    Async.task("AsyncInfoMonitorThread", () -> {
        threadCount = thread.getThreadCount();
        availableProcessors = r.availableProcessors();
        freeMemory = Runtime.getRuntime().freeMemory() / mb;
        maxMemory = Runtime.getRuntime().maxMemory() / mb;
        totalMemory = Runtime.getRuntime().totalMemory() / mb;
        cpuUsage = calculateCpuUsage(os);
        vpsCPUUsage = getVpsCPUUsage(os);
        vpsFreeMemory = calculateVPSFreeMemory(os);
        vpsMaxMemory = calculateVPSMaxMemory(os);
        vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
    }, 1);
    started = true;
}
 
Example 16
Project: QDrill   File: ThreadsIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final ThreadsInfo threadsInfo = new ThreadsInfo();

  final DrillbitEndpoint endpoint = context.getIdentity();
  threadsInfo.hostname = endpoint.getAddress();
  threadsInfo.user_port = endpoint.getUserPort();

  final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  threadsInfo.total_threads = threadMXBean.getPeakThreadCount();
  threadsInfo.busy_threads = threadMXBean.getThreadCount();
  return threadsInfo;
}
 
Example 17
Project: OpenJSharp   File: ThreadMonitor.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs a ThreadMonitor object to get thread information
 * in a remote JVM.
 */
public ThreadMonitor(MBeanServerConnection server) throws IOException {
   this.server = server;
   this.tmbean = newPlatformMXBeanProxy(server,
                                        THREAD_MXBEAN_NAME,
                                        ThreadMXBean.class);
   try {
       objname = new ObjectName(THREAD_MXBEAN_NAME);
    } catch (MalformedObjectNameException e) {
        // should not reach here
        InternalError ie = new InternalError(e.getMessage());
        ie.initCause(e);
        throw ie;
   }
   parseMBeanInfo();
}
 
Example 18
Project: OpenJSharp   File: JvmThreadInstanceEntryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Getter for the "JvmThreadInstCpuTimeNs" variable.
 */
public Long getJvmThreadInstCpuTimeNs() throws SnmpStatusException {
    long l = 0;
    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    try {
        if (tmb.isThreadCpuTimeSupported()) {
            l = tmb.getThreadCpuTime(info.getThreadId());
            log.debug("getJvmThreadInstCpuTimeNs", "Cpu time ns : " + l);

            //Cpu time measurement is disabled or the id is not valid.
            if(l == -1) l = 0;
        }
    } catch (UnsatisfiedLinkError e) {
        // XXX Revisit: catch TO BE EVENTUALLY REMOVED
        log.debug("getJvmThreadInstCpuTimeNs",
                  "Operation not supported: " + e);
    }
    return new Long(l);
}
 
Example 19
Project: OpenJSharp   File: JvmThreadingImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Getter for the "JvmThreadContentionMonitoring" variable.
 */
public EnumJvmThreadContentionMonitoring getJvmThreadContentionMonitoring()
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    if(!mbean.isThreadContentionMonitoringSupported()) {
        log.debug("getJvmThreadContentionMonitoring",
                  "Unsupported ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringUnsupported;
    }

    if(mbean.isThreadContentionMonitoringEnabled()) {
        log.debug("getJvmThreadContentionMonitoring",
                  "Enabled ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringEnabled;
    } else {
        log.debug("getJvmThreadContentionMonitoring",
                  "Disabled ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringDisabled;
    }
}
 
Example 20
Project: hadoop   File: TestShell.java   Source Code and License 6 votes vote down vote up
private static int countTimerThreads() {
  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("Timer")) {
        count++;
        break;
      }
    }
  }
  return count;
}
 
Example 21
Project: hadoop   File: TimedOutTestsListener.java   Source Code and License 6 votes vote down vote up
static String buildDeadlockInfo() {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  long[] threadIds = threadBean.findMonitorDeadlockedThreads();
  if (threadIds != null && threadIds.length > 0) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter out = new PrintWriter(stringWriter);
    
    ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
    for (ThreadInfo ti : infos) {
      printThreadInfo(ti, out);
      printLockInfo(ti.getLockedSynchronizers(), out);
      out.println();
    }
    
    out.close();
    return stringWriter.toString();
  } else {
    return null;
  }
}
 
Example 22
Project: hadoop   File: TestRPC.java   Source Code and License 6 votes vote down vote up
/**
 * Count the number of threads that have a stack frame containing
 * the given string
 */
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;
}
 
Example 23
Project: jdk8u-jdk   File: JvmThreadInstanceEntryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Getter for the "JvmThreadInstCpuTimeNs" variable.
 */
public Long getJvmThreadInstCpuTimeNs() throws SnmpStatusException {
    long l = 0;
    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    try {
        if (tmb.isThreadCpuTimeSupported()) {
            l = tmb.getThreadCpuTime(info.getThreadId());
            log.debug("getJvmThreadInstCpuTimeNs", "Cpu time ns : " + l);

            //Cpu time measurement is disabled or the id is not valid.
            if(l == -1) l = 0;
        }
    } catch (UnsatisfiedLinkError e) {
        // XXX Revisit: catch TO BE EVENTUALLY REMOVED
        log.debug("getJvmThreadInstCpuTimeNs",
                  "Operation not supported: " + e);
    }
    return new Long(l);
}
 
Example 24
Project: jdk8u-jdk   File: JvmThreadingImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Getter for the "JvmThreadContentionMonitoring" variable.
 */
public EnumJvmThreadContentionMonitoring getJvmThreadContentionMonitoring()
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    if(!mbean.isThreadContentionMonitoringSupported()) {
        log.debug("getJvmThreadContentionMonitoring",
                  "Unsupported ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringUnsupported;
    }

    if(mbean.isThreadContentionMonitoringEnabled()) {
        log.debug("getJvmThreadContentionMonitoring",
                  "Enabled ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringEnabled;
    } else {
        log.debug("getJvmThreadContentionMonitoring",
                  "Disabled ThreadContentionMonitoring");
        return JvmThreadContentionMonitoringDisabled;
    }
}
 
Example 25
Project: jdk8u-jdk   File: SharedSynchronizer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        MyThread t = new MyThread();
        t.setDaemon(true);
        t.start();

        ThreadMXBean tmbean = ManagementFactory.getThreadMXBean();
        if (!tmbean.isSynchronizerUsageSupported()) {
            System.out.println("Monitoring of synchronizer usage not supported")
;
            return;
        }

        long[] result = tmbean.findDeadlockedThreads();
        if (result != null) {
             throw new RuntimeException("TEST FAILED: result should be null");
        }
    }
 
Example 26
Project: jdk8u-jdk   File: GetInternalThreads.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    long value = mbean.getInternalThreadCount();

    if (value < MIN_VALUE_FOR_PASS || value > MAX_VALUE_FOR_PASS) {
        throw new RuntimeException("Internal thread count " +
                                   "illegal value: " + value + " " +
                                   "(MIN = " + MIN_VALUE_FOR_PASS + "; " +
                                   "MAX = " + MAX_VALUE_FOR_PASS + ")");
    }

    System.out.println("Internal Thread Count = " + value);

    ThreadMXBean thread =
        ManagementFactory.getThreadMXBean();
    if (!thread.isThreadCpuTimeSupported()) {
        System.out.println("Thread Cpu Time is not supported.");
        return;
    }

    while(!testCPUTime()) {
        Thread.sleep(100);
    }
}
 
Example 27
Project: ditb   File: TimedOutTestsListener.java   Source Code and License 6 votes vote down vote up
static String buildDeadlockInfo() {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  long[] threadIds = threadBean.findMonitorDeadlockedThreads();
  if (threadIds != null && threadIds.length > 0) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter out = new PrintWriter(stringWriter);
    
    ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
    for (ThreadInfo ti : infos) {
      printThreadInfo(ti, out);
      printLockInfo(ti.getLockedSynchronizers(), out);
      out.println();
    }
    
    out.close();
    return stringWriter.toString();
  } else {
    return null;
  }
}
 
Example 28
Project: jdk8u-jdk   File: TestThread.java   Source Code and License 6 votes vote down vote up
/**
 * Waits until {@link TestThread} is in the certain {@link State}
 * and blocking on {@code object}.
 *
 * @param state The thread state
 * @param object The object to block on
 */
public void waitUntilBlockingOnObject(Thread.State state, Object object) {
    String want = object == null ? null : object.getClass().getName() + '@'
            + Integer.toHexString(System.identityHashCode(object));
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(getId());
        if (ti.getThreadState() == state
                && (want == null || want.equals(ti.getLockName()))) {
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }
}
 
Example 29
Project: jsf-core   File: RegistryStatusServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String envi() {
    Map<String, String> result = new HashMap<String, String>();
    // 系统信息
    result.put(RegistryMonitorConstants.OSNAME, System.getProperty(RegistryMonitorConstants.OSNAME, "not specified"));
    result.put(RegistryMonitorConstants.JAVA_VERSION, System.getProperty(RegistryMonitorConstants.JAVA_VERSION, "not specified"));
    result.put(RegistryMonitorConstants.JDK_PATH, System.getProperty(RegistryMonitorConstants.JDK_PATH, "not specified"));
    result.put(RegistryMonitorConstants.APP_PATH, System.getProperty(RegistryMonitorConstants.APP_PATH, "not specified"));

    // jvm信息
    MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean();
    MemoryUsage usage = memorymbean.getHeapMemoryUsage();
    result.put(RegistryMonitorConstants.JVM_INIT, String.valueOf(usage.getInit()));
    result.put(RegistryMonitorConstants.JVM_MAX, String.valueOf(usage.getMax()));
    result.put(RegistryMonitorConstants.JVM_USED, String.valueOf(usage.getUsed()));
    
    //线程信息
    ThreadMXBean tm = (ThreadMXBean) ManagementFactory.getThreadMXBean();
    result.put(RegistryMonitorConstants.JVM_THREAD_COUNT, String.valueOf(tm.getThreadCount()));
    result.put(RegistryMonitorConstants.JVM_PEAKTHREAD_COUNT, String.valueOf(tm.getPeakThreadCount()));
    result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_CPUTIME, String.valueOf(tm.getCurrentThreadCpuTime()));
    result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_USERTIME, String.valueOf(tm.getCurrentThreadUserTime()));
    return JSON.toJSONString(result);
}
 
Example 30
Project: openjdk-jdk10   File: GraalOSRLockTest.java   Source Code and License 6 votes vote down vote up
public static boolean isMonitorLockHeldByThread(Object o, Thread t) {
    int oihc = System.identityHashCode(o);
    ThreadMXBean tmxbean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] tinfos = tmxbean.dumpAllThreads(true, false);

    for (ThreadInfo ti : tinfos) {
        if (!(t != null && t.getId() != ti.getThreadId())) {
            for (MonitorInfo mi : ti.getLockedMonitors()) {
                if (mi.getIdentityHashCode() == oihc) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 31
Project: openjdk-jdk10   File: ConcurrentAssociateTest.java   Source Code and License 6 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        String name = info.getThreadName();
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");
}
 
Example 32
Project: openjdk-jdk10   File: Basic.java   Source Code and License 6 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        String name = info.getThreadName();
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        if ("process reaper".equals(name))
            continue;
        if (name != null && name.startsWith("ForkJoinPool.commonPool-worker"))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");
}
 
Example 33
Project: openjdk-jdk10   File: GetInternalThreads.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    long value = mbean.getInternalThreadCount();

    if (value < MIN_VALUE_FOR_PASS || value > MAX_VALUE_FOR_PASS) {
        throw new RuntimeException("Internal thread count " +
                                   "illegal value: " + value + " " +
                                   "(MIN = " + MIN_VALUE_FOR_PASS + "; " +
                                   "MAX = " + MAX_VALUE_FOR_PASS + ")");
    }

    System.out.println("Internal Thread Count = " + value);

    ThreadMXBean thread =
        ManagementFactory.getThreadMXBean();
    if (!thread.isThreadCpuTimeSupported()) {
        System.out.println("Thread Cpu Time is not supported.");
        return;
    }

    while(!testCPUTime()) {
        Thread.sleep(100);
    }
}
 
Example 34
Project: openjdk-jdk10   File: ConnectorStopDeadlockTest.java   Source Code and License 6 votes vote down vote up
static void waitForBlock(Thread t) {
    Thread currentThread = Thread.currentThread();
    System.out.println("waiting for thread " + t.getName() + " to block " +
            "on a lock held by thread " + currentThread.getName());
    ThreadMXBean tm = ManagementFactory.getThreadMXBean();
    while (true) {
        ThreadInfo ti = tm.getThreadInfo(t.getId());
        if (ti == null) {
            System.out.println("  thread has exited");
            return;
        }
        if (ti.getLockOwnerId() == currentThread.getId()) {
            System.out.println("  thread now blocked");
            return;
        }
        Thread.yield();
    }
}
 
Example 35
Project: angel   File: WorkerService.java   Source Code and License 5 votes vote down vote up
private String getThreadStack() {
  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(true, true);
  StringBuilder stackTraceString = new StringBuilder("Worker\n");
  StringBuilder infoBlock = new StringBuilder("\n");
  for (ThreadInfo t : threadInfo) {
    infoBlock = new StringBuilder("\n\n");
    infoBlock.append("threadid: ").append(t.getThreadId()).append("   threadname: ").append(t.getThreadName()).append("       threadstate: ").append(t.getThreadState()).append("\n");
    for (StackTraceElement stackTraceElement : t.getStackTrace()) {
      infoBlock.append("   ").append(stackTraceElement.toString()).append("\n");
    }
    stackTraceString.append(infoBlock).append("\n\n");
  }
  return stackTraceString.toString();
}
 
Example 36
Project: hadoop-oss   File: GenericTestUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Determine if there are any threads whose name matches the regex.
 * @param pattern a Pattern object used to match thread names
 * @return true if there is any thread that matches the pattern
 */
public static boolean anyThreadMatching(Pattern pattern) {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

  ThreadInfo[] infos =
      threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
  for (ThreadInfo info : infos) {
    if (info == null)
      continue;
    if (pattern.matcher(info.getThreadName()).matches()) {
      return true;
    }
  }
  return false;
}
 
Example 37
Project: cornerstone   File: ThreadingManager.java   Source Code and License 5 votes vote down vote up
public static Map<String,Number> getThreadStats(){

        Map<String,Number> rtn = new HashMap<>();
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        rtn.put("currentThreadCount",threadBean.getThreadCount());
        rtn.put("daemonThreadCount", threadBean.getDaemonThreadCount());
        rtn.put("totalStartedThreadCount", threadBean.getTotalStartedThreadCount());
        rtn.put("peakThreadCount", threadBean.getPeakThreadCount());
        return rtn;
    }
 
Example 38
Project: OpenDA   File: OdaTiming.java   Source Code and License 5 votes vote down vote up
/** Get CPU time in nanoseconds. */

private long getCpuTime( ) {
	ThreadMXBean bean = null;
	try {
		bean = ManagementFactory.getThreadMXBean( );
	} catch (Error e) {
		// not supported (happens in the by means of IKVM converted version (.net)
		return 0L;
	}
	return bean.isCurrentThreadCpuTimeSupported( ) ?
        bean.getCurrentThreadCpuTime( ) : 0L;
}
 
Example 39
Project: rskj   File: VMExecutionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void thePathOfFifteenThousandJumps() {
    byte[] bytecode = new byte[15000 * 6 + 3];

    int k = 0;

    while (k < 15000 * 6) {
        int target = k + 6;
        bytecode[k++] = 0x5b; // JUMPDEST
        bytecode[k++] = 0x62; // PUSH3
        bytecode[k++] = (byte)(target >> 16);
        bytecode[k++] = (byte)(target >> 8);
        bytecode[k++] = (byte)(target & 0xff);
        bytecode[k++] = 0x56; // JUMP
    }

    bytecode[k++] = 0x5b; // JUMPDEST
    bytecode[k++] = 0x60; // PUSH1
    bytecode[k++] = 0x01; // 1

    ThreadMXBean thread = ManagementFactory.getThreadMXBean();

    Runtime runtime = Runtime.getRuntime();
    runtime.gc();
    long initialMemory = runtime.totalMemory() - runtime.freeMemory();
    long initialTime = thread.getCurrentThreadCpuTime();
    testCode(bytecode, 15000 * 3 + 2, "0000000000000000000000000000000000000000000000000000000000000001");
    long finalTime = thread.getCurrentThreadCpuTime();
    long finalMemory = runtime.totalMemory() - runtime.freeMemory();

    System.out.println(String.format("Execution Time %s nanoseconds", finalTime - initialTime));
    System.out.println(String.format("Delta memory %s", finalMemory - initialMemory));
}
 
Example 40
Project: openjdk-jdk10   File: ThreadMXBeanTool.java   Source Code and License 5 votes vote down vote up
/**
 * Waits until {@link Thread} is in native.
 */
public static void waitUntilInNative(Thread thread) throws InterruptedException {
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (thread.isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(thread.getId());
        if (ti.isInNative()) {
            return;
        }
        Thread.sleep(1);
    }
}
 
Example 41
Project: OpenJSharp   File: JvmThreadInstanceEntryImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadInstBlockTimeMs" variable.
 */
public Long getJvmThreadInstBlockTimeMs() throws SnmpStatusException {
    long l = 0;

    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    if (tmb.isThreadContentionMonitoringSupported()) {
        l = info.getBlockedTime();

        //Monitoring is disabled
        if(l == -1) l = 0;
    }
    return new Long(l);
}
 
Example 42
Project: OpenJSharp   File: JvmThreadInstanceEntryImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadInstWaitTimeMs" variable.
 */
public Long getJvmThreadInstWaitTimeMs() throws SnmpStatusException {
    long l = 0;

    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    if (tmb.isThreadContentionMonitoringSupported()) {
        l = info.getWaitedTime();

        //Monitoring is disabled
        if(l == -1) l = 0;
    }
    return new Long(l);
}
 
Example 43
Project: OpenJSharp   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadCpuTimeMonitoring" variable.
 */
public EnumJvmThreadCpuTimeMonitoring getJvmThreadCpuTimeMonitoring()
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    if(!mbean.isThreadCpuTimeSupported()) {
        log.debug("getJvmThreadCpuTimeMonitoring",
                  "Unsupported ThreadCpuTimeMonitoring");
        return JvmThreadCpuTimeMonitoringUnsupported;
    }

    try {
        if(mbean.isThreadCpuTimeEnabled()) {
            log.debug("getJvmThreadCpuTimeMonitoring",
                  "Enabled ThreadCpuTimeMonitoring");
            return JvmThreadCpuTimeMonitoringEnabled;
        } else {
            log.debug("getJvmThreadCpuTimeMonitoring",
                      "Disabled ThreadCpuTimeMonitoring");
            return JvmThreadCpuTimeMonitoringDisabled;
        }
    }catch(UnsupportedOperationException e) {
        log.debug("getJvmThreadCpuTimeMonitoring",
                  "Newly unsupported ThreadCpuTimeMonitoring");

        return JvmThreadCpuTimeMonitoringUnsupported;
    }
}
 
Example 44
Project: OpenJSharp   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Setter for the "JvmThreadCpuTimeMonitoring" variable.
 */
public void setJvmThreadCpuTimeMonitoring(EnumJvmThreadCpuTimeMonitoring x)
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    // We can trust the received value, it has been checked in
    // checkJvmThreadCpuTimeMonitoring
    if(JvmThreadCpuTimeMonitoringEnabled.intValue() == x.intValue())
        mbean.setThreadCpuTimeEnabled(true);
    else
        mbean.setThreadCpuTimeEnabled(false);
}
 
Example 45
Project: OpenJSharp   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Checker for the "JvmThreadCpuTimeMonitoring" variable.
 */
public void checkJvmThreadCpuTimeMonitoring(EnumJvmThreadCpuTimeMonitoring
                                            x)
    throws SnmpStatusException {

    //Can't be set externaly to unsupported state.
    if(JvmThreadCpuTimeMonitoringUnsupported.intValue() == x.intValue()) {
         log.debug("checkJvmThreadCpuTimeMonitoring",
                  "Try to set to illegal unsupported value");
        throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
    }

    if ((JvmThreadCpuTimeMonitoringEnabled.intValue() == x.intValue()) ||
        (JvmThreadCpuTimeMonitoringDisabled.intValue() == x.intValue())) {

        // The value is a valid value. But is the feature supported?
        ThreadMXBean mbean = getThreadMXBean();
        if(mbean.isThreadCpuTimeSupported()) return;

        // Not supported.
        log.debug("checkJvmThreadCpuTimeMonitoring",
                  "Unsupported operation, can't set state");
        throw new
            SnmpStatusException(SnmpDefinitions.snmpRspInconsistentValue);
    }

    // Unknown value.
    log.debug("checkJvmThreadCpuTimeMonitoring",
              "unknown enum value ");
    throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
}
 
Example 46
Project: OpenJSharp   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Checker for the "JvmThreadContentionMonitoring" variable.
 */
public void checkJvmThreadContentionMonitoring(
                          EnumJvmThreadContentionMonitoring x)
    throws SnmpStatusException {
    //Can't be set externaly to unsupported state.
    if(JvmThreadContentionMonitoringUnsupported.intValue()==x.intValue()) {
        log.debug("checkJvmThreadContentionMonitoring",
                  "Try to set to illegal unsupported value");
        throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
    }

    if ((JvmThreadContentionMonitoringEnabled.intValue()==x.intValue()) ||
        (JvmThreadContentionMonitoringDisabled.intValue()==x.intValue())) {

        // The value is valid, but is the feature supported ?
        ThreadMXBean mbean = getThreadMXBean();
        if(mbean.isThreadContentionMonitoringSupported()) return;

        log.debug("checkJvmThreadContentionMonitoring",
                  "Unsupported operation, can't set state");
        throw new
            SnmpStatusException(SnmpDefinitions.snmpRspInconsistentValue);
    }

    log.debug("checkJvmThreadContentionMonitoring",
              "Try to set to unknown value");
    throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
}
 
Example 47
Project: jsf-sdk   File: JVMStatusTelnetHandler.java   Source Code and License 5 votes vote down vote up
@Override
   public String telnet(Channel channel, String message) {
	StringBuilder sb = new StringBuilder();
	//内存使用情况
       MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
       long max = mmxb.getHeapMemoryUsage().getMax();
       long used = mmxb.getHeapMemoryUsage().getUsed();
       long init = mmxb.getHeapMemoryUsage().getInit();
       long commit = mmxb.getHeapMemoryUsage().getCommitted();
       sb.append("********Memory status******************").append(line);
       sb.append("Max JVM Heap Memory:").append(max / 1024 / 1024).append("M").append(line)
               .append("Used Heap Memory:").append(used / 1024 / 1024).append("M").append(line)
               .append("Init Heap Memory:").append(init / 1024 / 1024).append("M").append(line)
               .append("Commited Heap Memory:").append(commit/1024/1024).append("M").append(line);
       
       sb.append("********Thread status********************").append(line);
       //线程数
       ThreadMXBean txmb = ManagementFactory.getThreadMXBean();
       sb.append("Peak thread count:").append(txmb.getPeakThreadCount()).append("").append(line)
               .append("Thread count:").append(txmb.getThreadCount()).append("").append(line);

       sb.append("********Runtime status******************").append(line);
       //启动入口参数
       RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
       sb.append("InputArguments:[");
       for(String ia : rmxb.getInputArguments()){
       	sb.append(ia).append(",");
       }
       sb.deleteCharAt(sb.length()-1).append("]").append(line);
       sb.append("JVM start time:").append(DateUtils.dateToStr(new Date(rmxb.getStartTime()))).append(line);
       
       return sb.toString();
}
 
Example 48
Project: hadoop   File: GenericTestUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Assert that there are no threads running whose name matches the
 * given regular expression.
 * @param regex the regex to match against
 */
public static void assertNoThreadsMatching(String regex) {
  Pattern pattern = Pattern.compile(regex);
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  
  ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
  for (ThreadInfo info : infos) {
    if (info == null) continue;
    if (pattern.matcher(info.getThreadName()).matches()) {
      Assert.fail("Leaked thread: " + info + "\n" +
          Joiner.on("\n").join(info.getStackTrace()));
    }
  }
}
 
Example 49
Project: jdk8u-jdk   File: JvmThreadInstanceEntryImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadInstBlockTimeMs" variable.
 */
public Long getJvmThreadInstBlockTimeMs() throws SnmpStatusException {
    long l = 0;

    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    if (tmb.isThreadContentionMonitoringSupported()) {
        l = info.getBlockedTime();

        //Monitoring is disabled
        if(l == -1) l = 0;
    }
    return new Long(l);
}
 
Example 50
Project: jdk8u-jdk   File: JvmThreadInstanceEntryImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadInstWaitTimeMs" variable.
 */
public Long getJvmThreadInstWaitTimeMs() throws SnmpStatusException {
    long l = 0;

    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();

    if (tmb.isThreadContentionMonitoringSupported()) {
        l = info.getWaitedTime();

        //Monitoring is disabled
        if(l == -1) l = 0;
    }
    return new Long(l);
}
 
Example 51
Project: jdk8u-jdk   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the "JvmThreadCpuTimeMonitoring" variable.
 */
public EnumJvmThreadCpuTimeMonitoring getJvmThreadCpuTimeMonitoring()
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    if(!mbean.isThreadCpuTimeSupported()) {
        log.debug("getJvmThreadCpuTimeMonitoring",
                  "Unsupported ThreadCpuTimeMonitoring");
        return JvmThreadCpuTimeMonitoringUnsupported;
    }

    try {
        if(mbean.isThreadCpuTimeEnabled()) {
            log.debug("getJvmThreadCpuTimeMonitoring",
                  "Enabled ThreadCpuTimeMonitoring");
            return JvmThreadCpuTimeMonitoringEnabled;
        } else {
            log.debug("getJvmThreadCpuTimeMonitoring",
                      "Disabled ThreadCpuTimeMonitoring");
            return JvmThreadCpuTimeMonitoringDisabled;
        }
    }catch(UnsupportedOperationException e) {
        log.debug("getJvmThreadCpuTimeMonitoring",
                  "Newly unsupported ThreadCpuTimeMonitoring");

        return JvmThreadCpuTimeMonitoringUnsupported;
    }
}
 
Example 52
Project: jdk8u-jdk   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Setter for the "JvmThreadCpuTimeMonitoring" variable.
 */
public void setJvmThreadCpuTimeMonitoring(EnumJvmThreadCpuTimeMonitoring x)
    throws SnmpStatusException {

    ThreadMXBean mbean = getThreadMXBean();

    // We can trust the received value, it has been checked in
    // checkJvmThreadCpuTimeMonitoring
    if(JvmThreadCpuTimeMonitoringEnabled.intValue() == x.intValue())
        mbean.setThreadCpuTimeEnabled(true);
    else
        mbean.setThreadCpuTimeEnabled(false);
}
 
Example 53
Project: GabrielBot   File: DumpUtils.java   Source Code and License 5 votes vote down vote up
public static void dumpThreads(String file) throws IOException {
    StringBuilder dump = new StringBuilder();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
    for (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");
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(dump.toString().getBytes(Charset.defaultCharset()));
    try(FileOutputStream fos = new FileOutputStream(file)) {
        byte[] buffer = new byte[1024];
        int read;
        while((read = bais.read(buffer)) > -1) {
            fos.write(buffer, 0, read);
        }
    }
}
 
Example 54
Project: jdk8u-jdk   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Setter for the "JvmThreadContentionMonitoring" variable.
 */
public void setJvmThreadContentionMonitoring(
                        EnumJvmThreadContentionMonitoring x)
    throws SnmpStatusException {
    ThreadMXBean mbean = getThreadMXBean();

    // We can trust the received value, it has been checked in
    // checkJvmThreadContentionMonitoring
    if(JvmThreadContentionMonitoringEnabled.intValue() == x.intValue())
        mbean.setThreadContentionMonitoringEnabled(true);
    else
        mbean.setThreadContentionMonitoringEnabled(false);
}
 
Example 55
Project: jdk8u-jdk   File: JvmThreadingImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Checker for the "JvmThreadContentionMonitoring" variable.
 */
public void checkJvmThreadContentionMonitoring(
                          EnumJvmThreadContentionMonitoring x)
    throws SnmpStatusException {
    //Can't be set externaly to unsupported state.
    if(JvmThreadContentionMonitoringUnsupported.intValue()==x.intValue()) {
        log.debug("checkJvmThreadContentionMonitoring",
                  "Try to set to illegal unsupported value");
        throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
    }

    if ((JvmThreadContentionMonitoringEnabled.intValue()==x.intValue()) ||
        (JvmThreadContentionMonitoringDisabled.intValue()==x.intValue())) {

        // The value is valid, but is the feature supported ?
        ThreadMXBean mbean = getThreadMXBean();
        if(mbean.isThreadContentionMonitoringSupported()) return;

        log.debug("checkJvmThreadContentionMonitoring",
                  "Unsupported operation, can't set state");
        throw new
            SnmpStatusException(SnmpDefinitions.snmpRspInconsistentValue);
    }

    log.debug("checkJvmThreadContentionMonitoring",
              "Try to set to unknown value");
    throw new SnmpStatusException(SnmpDefinitions.snmpRspWrongValue);
}
 
Example 56
Project: jdk8u-jdk   File: AnnotationTypeDeadlockTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    CountDownLatch prepareLatch = new CountDownLatch(2);
    AtomicInteger goLatch = new AtomicInteger(1);
    Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
    Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
    taskA.start();
    taskB.start();
    // wait until both threads start-up
    prepareLatch.await();
    // let them go
    goLatch.set(0);
    // obtain ThreadMXBean
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    // wait for threads to finish or dead-lock
    while (taskA.isAlive() || taskB.isAlive()) {
        // attempt to join threads
        taskA.join(500L);
        taskB.join(500L);
        // detect dead-lock
        long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads();
        if (deadlockedIds != null && deadlockedIds.length > 0) {
            StringBuilder sb = new StringBuilder("deadlock detected:\n\n");
            for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) {
                sb.append(ti);
            }
            throw new IllegalStateException(sb.toString());
        }
    }
}
 
Example 57
Project: jdk8u-jdk   File: ThreadLists.java   Source Code and License 5 votes vote down vote up
public static void main(String args[]) {

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 58
Project: jdk8u-jdk   File: InvalidThreadID.java   Source Code and License 5 votes vote down vote up
public static void main(String argv[]) {

        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        int cnt = 0;
        long [] idArr = {0, -1, -2, (Long.MIN_VALUE + 1), Long.MIN_VALUE};

        if (mbean.isThreadCpuTimeSupported()) {
            for (int i = 0; i < idArr.length; i++) {
                try {
                    mbean.getThreadCpuTime(idArr[i]);
                    System.out.println("Test failed. IllegalArgumentException" +
                        " expected for ID = " + idArr[i]);
                } catch (IllegalArgumentException iae) {
                    cnt++;
                }
            }
            if (cnt != idArr.length) {
                throw new RuntimeException("Unexpected number of " +
                    "IllegalArgumentException = " + cnt +
                    " expected = " + idArr.length);
            }

            // CPU time for a non-existence thread
            long time = mbean.getThreadCpuTime(999999);
            if (time < 0 && time != -1) {
                throw new RuntimeException("Cpu time for thread 999999" +
                    " is invalid = " + time + " expected to be -1.");
            }
        }
        System.out.println("Test passed.");
    }
 
Example 59
Project: jdk8u-jdk   File: TestThread.java   Source Code and License 5 votes vote down vote up
/**
 * Waits until {@link TestThread} is in native.
 */
public void waitUntilInNative() {
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(getId());
        if (ti.isInNative()) {
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }
}
 
Example 60
Project: PEF   File: PcapSniffer.java   Source Code and License 5 votes vote down vote up
/**
 * Initialization of the pseudo packet handler which measures the time to handle the configured amount of bytes.
 *
 * @param pcap the interface with the pcap library needed to construct the packet handler.
 * @param MAX_BYTES the maximum amount of bytes captured
 * @return the handler for the packets.
 */
private static PcapPacketHandler<PseudoPacketHandler> getTimedByteLimitedHandler(final Pcap pcap, final long MAX_BYTES) {
    // Packet handler. Generic callback function for PseudoPacketHandler.
    return new PcapPacketHandler<PseudoPacketHandler>() {
        boolean started = false;
        long packetBytes = 0;
        long startTime;
        long stopTime;

        // A timer for performance tests.
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        // Handle nextPacket callback.
        public void nextPacket(PcapPacket packet, PseudoPacketHandler handler) {
            if (!started) {
                startTime = threadMXBean.getCurrentThreadCpuTime();
                logger.info("Started at "+ startTime);
                started = true;
            }
            handler.handle(packet);

            packetBytes+= packet.size();
            if (packetBytes >= MAX_BYTES) {
                stopTime = threadMXBean.getCurrentThreadCpuTime();
                pcap.breakloop();
                logger.info("Stopped after " + ((stopTime - startTime)/10000000000.0) + " seconds and " + packetBytes + " bytes.");
            }
        }
    };
}