use of java.lang.management.ThreadMXBean in project karaf by apache.
the class ThreadsAction method execute.
@Override
public Object execute() throws Exception {
Map<Long, ThreadInfo> threadInfos = new TreeMap<>();
ThreadMXBean threadsBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos;
if (threadsBean.isObjectMonitorUsageSupported() && threadsBean.isSynchronizerUsageSupported()) {
infos = threadsBean.dumpAllThreads(true, true);
} else {
infos = threadsBean.getThreadInfo(threadsBean.getAllThreadIds(), Integer.MAX_VALUE);
}
for (ThreadInfo info : infos) {
threadInfos.put(info.getThreadId(), info);
}
if (id != null) {
ThreadInfo ti = threadInfos.get(id);
if (ti != null) {
System.out.println("Thread " + ti.getThreadId() + " " + ti.getThreadName() + " " + ti.getThreadState());
System.out.println("Stacktrace:");
StackTraceElement[] st = ti.getStackTrace();
for (StackTraceElement ste : st) {
System.out.println(ste.getClassName() + "." + ste.getMethodName() + " line: " + ste.getLineNumber());
}
}
} else if (list) {
ShellTable table = new ShellTable();
table.column("Id");
table.column("Name");
table.column("State");
table.column("CPU time");
table.column("Usr time");
for (ThreadInfo thread : threadInfos.values()) {
long id = thread.getThreadId();
table.addRow().addContent(id, thread.getThreadName(), thread.getThreadState(), threadsBean.getThreadCpuTime(id) / 1000000, threadsBean.getThreadUserTime(id) / 1000000);
}
table.print(System.out, !noFormat);
} else {
ThreadGroup group = Thread.currentThread().getThreadGroup();
while (group.getParent() != null) {
group = group.getParent();
}
ThreadGroupData data = new ThreadGroupData(group, threadInfos);
data.print();
}
return null;
}
use of java.lang.management.ThreadMXBean in project karaf by apache.
the class ConfigProperties method performInit.
public void performInit() throws Exception {
File cleanAllIndicatorFile = new File(karafData, "clean_all");
File cleanCacheIndicatorFile = new File(karafData, "clean_cache");
if (Boolean.getBoolean("karaf.clean.all") || cleanAllIndicatorFile.exists()) {
if (cleanAllIndicatorFile.exists()) {
cleanAllIndicatorFile.delete();
}
Utils.deleteDirectory(this.karafData);
this.karafData = Utils.getKarafDirectory(PROP_KARAF_DATA, ENV_KARAF_DATA, new File(karafBase, "data"), true, true);
} else {
if (Boolean.getBoolean("karaf.clean.cache") || cleanCacheIndicatorFile.exists()) {
if (cleanCacheIndicatorFile.exists()) {
cleanCacheIndicatorFile.delete();
}
File karafCache = Utils.validateDirectoryExists(new File(karafData, "cache").getPath(), "Invalid cache directory", true, true);
Utils.deleteDirectory(karafCache);
}
}
String frameworkStoragePath = props.getProperty(Constants.FRAMEWORK_STORAGE);
if (frameworkStoragePath == null) {
File storage = new File(karafData.getPath(), "cache");
try {
storage.mkdirs();
} catch (SecurityException se) {
throw new Exception(se.getMessage());
}
props.setProperty(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());
}
if (shutdownCommand == null || shutdownCommand.isEmpty()) {
try {
shutdownCommand = UUID.randomUUID().toString();
Properties temp = new Properties(new File(karafEtc, CONFIG_PROPERTIES_FILE_NAME));
temp.put(KARAF_SHUTDOWN_COMMAND, Arrays.asList("", "#", "# Generated command shutdown", "#"), shutdownCommand);
temp.save();
} catch (IOException ioException) {
System.err.println("WARN: can't update etc/config.properties with the generated command shutdown. We advise to manually add the karaf.shutdown.command property.");
}
}
if (threadMonitoring) {
ThreadMXBean threadsBean = ManagementFactory.getThreadMXBean();
if (threadsBean.isThreadCpuTimeSupported()) {
threadsBean.setThreadCpuTimeEnabled(true);
}
if (threadsBean.isThreadContentionMonitoringSupported()) {
threadsBean.setThreadContentionMonitoringEnabled(true);
}
}
}
use of java.lang.management.ThreadMXBean in project jena by apache.
the class ConcurrencyTest method doTestConcurrency.
private void doTestConcurrency(final OntModel model) throws InterruptedException {
// initialize the model
final String NS = PrintUtil.egNS;
model.enterCriticalSection(Lock.WRITE);
final OntClass Top = model.createClass(NS + "Top");
for (int i = 0; i < MODEL_SIZE; i++) {
OntClass C = model.createClass(NS + "C" + i);
Top.addSubClass(C);
model.createIndividual(NS + "i" + i, C);
}
model.leaveCriticalSection();
class QueryExecutingRunnable implements Runnable {
@Override
@SuppressWarnings("unchecked")
public void run() {
// Keep this thread running until the specified duration has expired
long runStartedAt = System.currentTimeMillis();
while (System.currentTimeMillis() - runStartedAt < TEST_LENGTH) {
Thread.yield();
model.enterCriticalSection(Lock.READ);
try {
// Iterate over all statements
StmtIterator it = model.listStatements();
while (it.hasNext()) it.nextStatement();
it.close();
// Check number of instances of Top class
int count = 0;
ExtendedIterator<OntResource> ei = (ExtendedIterator<OntResource>) Top.listInstances();
while (ei.hasNext()) {
ei.next();
count++;
}
ei.close();
if (MODEL_SIZE != count) {
if (FULL_TEST)
System.err.println("Failure - found " + count + " instance, expected " + MODEL_SIZE);
throw new JenaException("Failure - found " + count + " instance, expected " + MODEL_SIZE);
}
} finally {
model.leaveCriticalSection();
}
}
}
}
// Start the threads
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; ++i) {
executorService.submit(new QueryExecutingRunnable());
}
// Wait for threads to finish
// this will *not* terminate any threads currently running
executorService.shutdown();
Thread.sleep(TEST_LENGTH + 50);
// Possibly in deadlock, wait a little longer to be sure
for (int i = 0; i < 50 && !executorService.isTerminated(); i++) {
Thread.sleep(20);
}
if (!executorService.isTerminated()) {
/* uncomment this block to perform deadlock checking, only on java 1.6 */
// Check for deadlock
ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
long[] ids = tmx.findDeadlockedThreads();
if (ids != null) {
ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);
System.err.println("*** Deadlocked threads");
for (ThreadInfo ti : infos) {
System.err.println("Thread \"" + ti.getThreadName() + "\" id=" + ti.getThreadId() + " " + ti.getThreadState().toString());
System.err.println("Lock name: " + ti.getLockName() + " owned by \"" + ti.getLockOwnerName() + "\" id=" + ti.getLockOwnerId());
System.err.println("\nStack trace:");
for (StackTraceElement st : ti.getStackTrace()) System.err.println(" " + st.getClassName() + "." + st.getMethodName() + " (" + st.getFileName() + ":" + st.getLineNumber() + ")");
System.err.println();
}
}
Assert.assertTrue("Deadlock detected!", false);
/* end deadlock block */
assertTrue("Failed to terminate execution", false);
}
}
use of java.lang.management.ThreadMXBean in project sling by apache.
the class ThreadUsageHealthCheck method execute.
@Override
public Result execute() {
FormattingResultLog log = new FormattingResultLog();
log.debug("Checking threads for exceeding {}% CPU time within time period of {}ms", cpuTimeThresholdWarn, samplePeriodInMs);
try {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
List<ThreadTimeInfo> threadTimeInfos = collectThreadTimeInfos(log, threadMxBean);
Collections.sort(threadTimeInfos);
float totalCpuTimePercentage = 0;
for (int i = 0; i < threadTimeInfos.size(); i++) {
ThreadTimeInfo threadInfo = threadTimeInfos.get(i);
float cpuTimePercentage = ((float) threadInfo.getCpuTime() / ((float) samplePeriodInMs * 1000000)) * 100f;
totalCpuTimePercentage += cpuTimePercentage;
String msg = String.format("%4.1f", cpuTimePercentage) + "% used by thread \"" + threadInfo.name + "\"";
if (i < 3 || (i < 10 && cpuTimePercentage > 15)) {
log.info(msg);
} else {
log.debug(msg);
}
}
log.info(threadTimeInfos.size() + " threads using " + String.format("%4.1f", totalCpuTimePercentage) + "% CPU Time");
boolean isHighCpuTime = totalCpuTimePercentage > cpuTimeThresholdWarn;
if (isHighCpuTime) {
log.warn("Threads are consuming significant CPU time " + (cpuTimeThresholdWarnIsConfigured ? "(more than configured " + cpuTimeThresholdWarn + "% within " + samplePeriodInMs + "ms)" : "(more than " + availableProcessors + " cores * 90% = " + cpuTimeThresholdWarn + "%)"));
}
checkForDeadlock(log, threadMxBean);
} catch (Exception e) {
LOG.error("Could not analyse thread usage " + e, e);
log.healthCheckError("Could not analyse thread usage", e);
}
return new Result(log);
}
use of java.lang.management.ThreadMXBean in project spring-boot by spring-projects.
the class SystemPublicMetrics method addThreadMetrics.
/**
* Add thread metrics.
* @param result the result
*/
protected void addThreadMetrics(Collection<Metric<?>> result) {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
result.add(new Metric<>("threads.peak", (long) threadMxBean.getPeakThreadCount()));
result.add(new Metric<>("threads.daemon", (long) threadMxBean.getDaemonThreadCount()));
result.add(new Metric<>("threads.totalStarted", threadMxBean.getTotalStartedThreadCount()));
result.add(new Metric<>("threads", (long) threadMxBean.getThreadCount()));
}
Aggregations