List of usage examples for java.lang.management ManagementFactory getThreadMXBean
public static ThreadMXBean getThreadMXBean()
From source file:com.hs.mail.container.simple.SimpleSpringContainer.java
private static void startPerformanceMonitor(String interval) { int period = Integer.parseInt(interval); Timer timer = new Timer(); TimerTask memoryTask = new TimerTask() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); @Override/*from ww w . j av a2 s.com*/ public void run() { int threadCount = threadBean.getThreadCount(); int peakThreadCount = threadBean.getPeakThreadCount(); MemoryUsage heap = memoryBean.getHeapMemoryUsage(); MemoryUsage nonHeap = memoryBean.getNonHeapMemoryUsage(); System.out.println(sdf.format(System.currentTimeMillis()) + "\t threads=" + threadCount + ";peakThreads=" + peakThreadCount + ";heap=" + heap + ";non-heap=" + nonHeap); } }; timer.schedule(memoryTask, 0, period * 1000); }
From source file:models.monitor.MonitorProvider.java
public ThreadUsage getThreadUsage() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); ThreadUsage threadUsage = new ThreadUsage(); long[] threadIds = threadMxBean.getAllThreadIds(); threadUsage.liveThreadCount = threadIds.length; for (long tId : threadIds) { ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId); threadUsage.threadData.put(new Long(tId).toString(), new ThreadData(threadInfo.getThreadName(), threadInfo.getThreadState().name(), threadMxBean.getThreadCpuTime(tId))); }/*from w w w. j a va 2 s. co m*/ return threadUsage; }
From source file:eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl.java
public TaskManagerProfilerImpl(InetAddress jobManagerAddress, InstanceConnectionInfo instanceConnectionInfo) throws ProfilingException { // Create RPC stub for communication with job manager's profiling component. final InetSocketAddress profilingAddress = new InetSocketAddress(jobManagerAddress, GlobalConfiguration .getInteger(ProfilingUtils.JOBMANAGER_RPC_PORT_KEY, ProfilingUtils.JOBMANAGER_DEFAULT_RPC_PORT)); ProfilerImplProtocol jobManagerProfilerTmp = null; try {//w ww .j av a2 s . co m jobManagerProfilerTmp = (ProfilerImplProtocol) RPC.getProxy(ProfilerImplProtocol.class, profilingAddress, NetUtils.getSocketFactory()); } catch (IOException e) { throw new ProfilingException(StringUtils.stringifyException(e)); } this.jobManagerProfiler = jobManagerProfilerTmp; // Initialize MX interface and check if thread contention monitoring is supported this.tmx = ManagementFactory.getThreadMXBean(); if (this.tmx.isThreadContentionMonitoringSupported()) { this.tmx.setThreadContentionMonitoringEnabled(true); } else { throw new ProfilingException("The thread contention monitoring is not supported."); } // Create instance profiler this.instanceProfiler = new InstanceProfiler(instanceConnectionInfo); // Set and trigger timer this.timerInterval = (long) (GlobalConfiguration.getInteger(ProfilingUtils.TASKMANAGER_REPORTINTERVAL_KEY, ProfilingUtils.DEFAULT_TASKMANAGER_REPORTINTERVAL) * 1000); // The initial delay is based on a random value, so the task managers will not send data to the job manager all // at once. final long initialDelay = (long) (Math.random() * this.timerInterval); this.timer = new Timer(true); this.timer.schedule(this, initialDelay, this.timerInterval); }
From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java
@GET @RequireAdmin//www. j ava 2s .c o m @APIDescription("Gets the application system status") @Produces({ MediaType.APPLICATION_JSON }) @DataType(ApplicationStatus.class) @Path("/status") public Response getApplicationStatus() { OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ApplicationStatus applicationStatus = new ApplicationStatus(); applicationStatus.setApplicationVersion(PropertiesManager.getApplicationVersion()); applicationStatus.setProcessorCount(operatingSystemMXBean.getAvailableProcessors()); applicationStatus.setSystemLoad(operatingSystemMXBean.getSystemLoadAverage()); applicationStatus.setSystemProperties(runtimeMXBean.getSystemProperties()); applicationStatus.getHeapMemoryStatus().setName("Heap"); applicationStatus.getHeapMemoryStatus().setDetails(memoryMXBean.getHeapMemoryUsage().toString()); applicationStatus.getHeapMemoryStatus() .setInitKb(memoryMXBean.getHeapMemoryUsage().getInit() != 0 ? memoryMXBean.getHeapMemoryUsage().getInit() / 1024 : 0); applicationStatus.getHeapMemoryStatus() .setUsedKb(memoryMXBean.getHeapMemoryUsage().getUsed() != 0 ? memoryMXBean.getHeapMemoryUsage().getUsed() / 1024 : 0); applicationStatus.getHeapMemoryStatus() .setMaxKb(memoryMXBean.getHeapMemoryUsage().getMax() != 0 ? memoryMXBean.getHeapMemoryUsage().getMax() / 1024 : 0); applicationStatus.getHeapMemoryStatus() .setCommitedKb(memoryMXBean.getHeapMemoryUsage().getCommitted() != 0 ? memoryMXBean.getHeapMemoryUsage().getCommitted() / 1024 : 0); applicationStatus.getNonHeapMemoryStatus().setName("Non-Heap"); applicationStatus.getNonHeapMemoryStatus().setDetails(memoryMXBean.getNonHeapMemoryUsage().toString()); applicationStatus.getNonHeapMemoryStatus() .setInitKb(memoryMXBean.getNonHeapMemoryUsage().getInit() != 0 ? memoryMXBean.getNonHeapMemoryUsage().getInit() / 1024 : 0); applicationStatus.getNonHeapMemoryStatus() .setUsedKb(memoryMXBean.getNonHeapMemoryUsage().getUsed() != 0 ? memoryMXBean.getNonHeapMemoryUsage().getUsed() / 1024 : 0); applicationStatus.getNonHeapMemoryStatus() .setMaxKb(memoryMXBean.getNonHeapMemoryUsage().getMax() != 0 ? memoryMXBean.getNonHeapMemoryUsage().getMax() / 1024 : 0); applicationStatus.getNonHeapMemoryStatus() .setCommitedKb(memoryMXBean.getNonHeapMemoryUsage().getCommitted() != 0 ? memoryMXBean.getNonHeapMemoryUsage().getCommitted() / 1024 : 0); applicationStatus.setLiveThreadCount(threadMXBean.getThreadCount()); applicationStatus.setTotalThreadCount(threadMXBean.getTotalStartedThreadCount()); applicationStatus.setStartTime(new Date(runtimeMXBean.getStartTime())); applicationStatus.setUpTime(TimeUtil.millisToString(runtimeMXBean.getUptime())); for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) { applicationStatus.getGarbageCollectionInfos() .add(TimeUtil.millisToString(garbageCollectorMXBean.getCollectionTime()) + " - (" + garbageCollectorMXBean.getCollectionCount() + ")"); } for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { MemoryPoolStatus memoryPoolStatus = new MemoryPoolStatus(); memoryPoolStatus.setName(memoryPoolMXBean.getName() + " - " + memoryPoolMXBean.getType()); memoryPoolStatus.setDetails(memoryPoolMXBean.getUsage().toString()); memoryPoolStatus.setInitKb( memoryPoolMXBean.getUsage().getInit() != 0 ? memoryPoolMXBean.getUsage().getInit() / 1024 : 0); memoryPoolStatus.setUsedKb( memoryPoolMXBean.getUsage().getUsed() != 0 ? memoryPoolMXBean.getUsage().getUsed() / 1024 : 0); memoryPoolStatus.setMaxKb( memoryPoolMXBean.getUsage().getMax() != 0 ? memoryPoolMXBean.getUsage().getMax() / 1024 : 0); memoryPoolStatus.setCommitedKb(memoryPoolMXBean.getUsage().getCommitted() != 0 ? memoryPoolMXBean.getUsage().getCommitted() / 1024 : 0); applicationStatus.getMemoryPools().add(memoryPoolStatus); } return sendSingleEntityResponse(applicationStatus); }
From source file:org.alfresco.extension.bulkimport.util.LogUtils.java
public final static String dumpThread(final String threadName) { final StringBuilder result = new StringBuilder(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); final ThreadInfo[] threadsInfo = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (final ThreadInfo threadInfo : threadsInfo) { if (threadName == null || threadName.equals(threadInfo.getThreadName())) { result.append("\nName: "); result.append(threadInfo.getThreadName()); result.append("\nState: "); result.append(threadInfo.getThreadState()); result.append("\nStack Trace:"); for (final StackTraceElement stackTraceElement : threadInfo.getStackTrace()) { result.append("\n\t\tat "); result.append(stackTraceElement); }//from w w w. j a v a 2 s .c om } } return (result.toString()); }
From source file:ca.simplegames.micro.controllers.StatsController.java
public void execute(MicroContext context, Map configuration) throws ControllerException { Map<String, Object> systemInfo = new HashMap<String, Object>(); Map<String, Object> osMap = new HashMap<String, Object>(); MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer(); OperatingSystemMXBean sunOperatingSystemMXBean = null; try {/*from ww w.jav a2 s .c o m*/ sunOperatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServer, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); } catch (IOException e) { throw new ControllerException(e.getMessage()); } Runtime rt = Runtime.getRuntime(); long totalMemory = rt.totalMemory() / MEGA_BYTE; long freeMemory = rt.freeMemory() / MEGA_BYTE; long usedMemory = totalMemory - freeMemory; final long p100 = (int) Math.round(((double) freeMemory / (double) totalMemory) * 100); Map<String, Long> memInfo = new HashMap<String, Long>(); memInfo.put("total", totalMemory); memInfo.put("used", usedMemory); memInfo.put("free", freeMemory); memInfo.put("percent_free", p100); systemInfo.put("memory", memInfo); systemInfo.put("powered_by", POWERED_BY_MICRO); //cpu usage in milli secs long currentCpuUsage = sunOperatingSystemMXBean.getProcessCpuTime() / 1000000; osMap.put("cpu_usage", currentCpuUsage); osMap.put("available_processors", sunOperatingSystemMXBean.getAvailableProcessors()); osMap.put("system_load_average", sunOperatingSystemMXBean.getSystemLoadAverage()); osMap.put("committed_virtual_memory_size", sunOperatingSystemMXBean.getCommittedVirtualMemorySize()); osMap.put("free_physical_memory_size", sunOperatingSystemMXBean.getFreePhysicalMemorySize()); osMap.put("total_physical_memory_size", sunOperatingSystemMXBean.getTotalPhysicalMemorySize()); osMap.put("free_swap_space_size", sunOperatingSystemMXBean.getFreeSwapSpaceSize()); osMap.put("total_swap_space_size", sunOperatingSystemMXBean.getTotalSwapSpaceSize()); systemInfo.put("os", osMap); List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans(); List<Map> gcInfo = new ArrayList<Map>(); for (GarbageCollectorMXBean aGc : gc) { Map<String, Object> gcMap = new HashMap<String, Object>(); gcMap.put("name", aGc.getName()); gcMap.put("collection_count", aGc.getCollectionCount()); gcMap.put("collection_time", aGc.getCollectionTime()); gcInfo.add(gcMap); } systemInfo.put("gc", gcInfo); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); Map<String, Object> threadInfoMap = new HashMap<String, Object>(); // more to come ;) threadInfoMap.put("peak_thread_count", threadMXBean.getPeakThreadCount()); threadInfoMap.put("thread_count", threadMXBean.getThreadCount()); threadInfoMap.put("total_started_thread_count", threadMXBean.getTotalStartedThreadCount()); long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads(); threadInfoMap.put("dead_locked_thread_count", deadlockedThreads != null ? deadlockedThreads.length : 0); systemInfo.put("thread_info", threadInfoMap); JSONObject sysinfoJson = new JSONObject(Collections.singletonMap("system_info", systemInfo)); String sysinfoString = null; try { sysinfoString = context.getRequest().getParameter("pretty") != null ? sysinfoJson.toString(2) : sysinfoJson.toString(); } catch (JSONException e) { e.printStackTrace(); throw new ControllerException(e.getMessage()); } context.getRackResponse().withContentType(Mime.mimeType(JSON_TYPE)).withBody(sysinfoString) .withContentLength(sysinfoString.length()).with(Rack.MESSAGE_STATUS, HttpServletResponse.SC_OK); context.halt(); }
From source file:org.apache.asterix.test.runtime.LangExecutionUtil.java
private static void checkThreadLeaks() throws IOException { String threadDump = ThreadDumpHelper.takeDumpJSON(ManagementFactory.getThreadMXBean()); // Currently we only do sanity check for threads used in the execution engine. // Later we should check if there are leaked storage threads as well. if (threadDump.contains("Operator") || threadDump.contains("SuperActivity") || threadDump.contains("PipelinedPartition")) { System.out.print(threadDump); throw new AssertionError("There are leaked threads in the execution engine."); }/*from ww w . j a va 2 s . c o m*/ }
From source file:com.snowstore.mercury.core.metric.SystemPublicMetrics.java
/** * Add thread metrics.//from www.j av a2 s. c o m * * @param result * the result */ protected void addThreadMetrics(Collection<Metric<?>> result) { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); result.add(new Metric<Long>("threads.peak", (long) threadMxBean.getPeakThreadCount())); result.add(new Metric<Long>("threads.daemon", (long) threadMxBean.getDaemonThreadCount())); result.add(new Metric<Long>("threads", (long) threadMxBean.getThreadCount())); }
From source file:sk.baka.webvm.analyzer.Deadlock.java
/** * Checks that the threads are running and no exception was thrown. *//*from w ww . j a v a 2 s .c o m*/ @Test public void checkThreads() { assertNull("An exception was thrown while forming a deadlock: " + t, t); assertTrue("Both threads must be alive as they are deadlocked", t1.isAlive()); assertTrue("Both threads must be alive as they are deadlocked", t2.isAlive()); // sanity-check for JVM to report correct values final long ids[] = ProblemAnalyzer.findDeadlockedThreads(ManagementFactory.getThreadMXBean()); // this assumption fails on 1.5 as it does not support finding deadlocks in a ReentrantLock. // we could form a deadlock using the synchronized keyword but there is no way to interrupt // wait in the synchronized block thus the threads will never end - this will interfere with other tests. // Just skip the tests on 1.5. if (SystemUtils.isJavaVersionAtLeast(160)) { assertTrue("Two threads are expected to be deadlocked, but the following was found: " + (ids == null ? "null" : Arrays.toString(ids)), ids != null && ids.length == 2); } }
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 w w . j a 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); }