use of java.lang.management.ThreadMXBean in project elasticsearch by elastic.
the class SimpleThreadPoolIT method testThreadNames.
public void testThreadNames() throws Exception {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
Set<String> preNodeStartThreadNames = new HashSet<>();
for (long l : threadBean.getAllThreadIds()) {
ThreadInfo threadInfo = threadBean.getThreadInfo(l);
if (threadInfo != null) {
preNodeStartThreadNames.add(threadInfo.getThreadName());
}
}
logger.info("pre node threads are {}", preNodeStartThreadNames);
String node = internalCluster().startNode();
logger.info("do some indexing, flushing, optimize, and searches");
int numDocs = randomIntBetween(2, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; ++i) {
builders[i] = client().prepareIndex("idx", "type").setSource(jsonBuilder().startObject().field("str_value", "s" + i).array("str_values", new String[] { "s" + (i * 2), "s" + (i * 2 + 1) }).field("l_value", i).array("l_values", new int[] { i * 2, i * 2 + 1 }).field("d_value", i).array("d_values", new double[] { i * 2, i * 2 + 1 }).endObject());
}
indexRandom(true, builders);
int numSearches = randomIntBetween(2, 100);
for (int i = 0; i < numSearches; i++) {
assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("str_value", "s" + i)).get());
assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("l_value", i)).get());
}
Set<String> threadNames = new HashSet<>();
for (long l : threadBean.getAllThreadIds()) {
ThreadInfo threadInfo = threadBean.getThreadInfo(l);
if (threadInfo != null) {
threadNames.add(threadInfo.getThreadName());
}
}
logger.info("post node threads are {}", threadNames);
threadNames.removeAll(preNodeStartThreadNames);
logger.info("post node *new* threads are {}", threadNames);
for (String threadName : threadNames) {
// or the ones that are occasionally come up from ESSingleNodeTestCase
if (// TODO: this can't possibly be right! single node and integ test are unrelated!
threadName.contains("[node_s_0]") || threadName.contains("Keep-Alive-Timer")) {
continue;
}
String nodePrefix = "(" + Pattern.quote(InternalTestCluster.TRANSPORT_CLIENT_PREFIX) + ")?(" + Pattern.quote(ESIntegTestCase.SUITE_CLUSTER_NODE_PREFIX) + "|" + Pattern.quote(ESIntegTestCase.TEST_CLUSTER_NODE_PREFIX) + "|" + Pattern.quote("node_tribe2") + ")";
assertThat(threadName, RegexMatcher.matches("\\[" + nodePrefix + "\\d+\\]"));
}
}
use of java.lang.management.ThreadMXBean in project elasticsearch by elastic.
the class CacheTests method testDependentKeyDeadlock.
public void testDependentKeyDeadlock() throws BrokenBarrierException, InterruptedException {
class Key {
private final int key;
Key(int key) {
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Key key1 = (Key) o;
return key == key1.key;
}
@Override
public int hashCode() {
return key % 2;
}
}
int numberOfThreads = randomIntBetween(2, 32);
final Cache<Key, Integer> cache = CacheBuilder.<Key, Integer>builder().build();
CopyOnWriteArrayList<ExecutionException> failures = new CopyOnWriteArrayList<>();
CyclicBarrier barrier = new CyclicBarrier(1 + numberOfThreads);
CountDownLatch deadlockLatch = new CountDownLatch(numberOfThreads);
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(() -> {
try {
try {
barrier.await();
} catch (BrokenBarrierException | InterruptedException e) {
throw new AssertionError(e);
}
Random random = new Random(random().nextLong());
for (int j = 0; j < numberOfEntries; j++) {
Key key = new Key(random.nextInt(numberOfEntries));
try {
cache.computeIfAbsent(key, k -> {
if (k.key == 0) {
return 0;
} else {
Integer value = cache.get(new Key(k.key / 2));
return value != null ? value : 0;
}
});
} catch (ExecutionException e) {
failures.add(e);
break;
}
}
} finally {
// successfully avoided deadlock, release the main thread
deadlockLatch.countDown();
}
});
threads.add(thread);
thread.start();
}
AtomicBoolean deadlock = new AtomicBoolean();
assert !deadlock.get();
// start a watchdog service
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
Set<Long> ids = threads.stream().map(t -> t.getId()).collect(Collectors.toSet());
ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
long[] deadlockedThreads = mxBean.findDeadlockedThreads();
if (!deadlock.get() && deadlockedThreads != null) {
for (long deadlockedThread : deadlockedThreads) {
// ensure that we detected deadlock on our threads
if (ids.contains(deadlockedThread)) {
deadlock.set(true);
// release the main test thread to fail the test
for (int i = 0; i < numberOfThreads; i++) {
deadlockLatch.countDown();
}
break;
}
}
}
}, 1, 1, TimeUnit.SECONDS);
// everything is setup, release the hounds
barrier.await();
// wait for either deadlock to be detected or the threads to terminate
deadlockLatch.await();
// shutdown the watchdog service
scheduler.shutdown();
assertThat(failures, is(empty()));
assertFalse("deadlock", deadlock.get());
}
use of java.lang.management.ThreadMXBean in project sonarqube by SonarSource.
the class ProcessStateSystemInfo method toProtobuf.
// Visible for testing
ProtobufSystemInfo.Section toProtobuf(MemoryMXBean memoryBean) {
ProtobufSystemInfo.Section.Builder builder = ProtobufSystemInfo.Section.newBuilder();
builder.setName(name);
MemoryUsage heap = memoryBean.getHeapMemoryUsage();
addAttributeInMb(builder, "Heap Committed (MB)", heap.getCommitted());
addAttributeInMb(builder, "Heap Init (MB)", heap.getInit());
addAttributeInMb(builder, "Heap Max (MB)", heap.getMax());
addAttributeInMb(builder, "Heap Used (MB)", heap.getUsed());
MemoryUsage nonHeap = memoryBean.getNonHeapMemoryUsage();
addAttributeInMb(builder, "Non Heap Committed (MB)", nonHeap.getCommitted());
addAttributeInMb(builder, "Non Heap Init (MB)", nonHeap.getInit());
addAttributeInMb(builder, "Non Heap Max (MB)", nonHeap.getMax());
addAttributeInMb(builder, "Non Heap Used (MB)", nonHeap.getUsed());
ThreadMXBean thread = ManagementFactory.getThreadMXBean();
builder.addAttributesBuilder().setKey("Thread Count").setLongValue(thread.getThreadCount()).build();
return builder.build();
}
use of java.lang.management.ThreadMXBean in project disruptor by LMAX-Exchange.
the class BasicExecutor method dumpThreadInfo.
private String dumpThreadInfo() {
final StringBuilder sb = new StringBuilder();
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
for (Thread t : threads) {
ThreadInfo threadInfo = threadMXBean.getThreadInfo(t.getId());
sb.append("{");
sb.append("name=").append(t.getName()).append(",");
sb.append("id=").append(t.getId()).append(",");
sb.append("state=").append(threadInfo.getThreadState()).append(",");
sb.append("lockInfo=").append(threadInfo.getLockInfo());
sb.append("}");
}
return sb.toString();
}
use of java.lang.management.ThreadMXBean in project presto by prestodb.
the class ThreadResource method getThreadInfo.
@GET
@Path("/v1/thread")
@Produces(MediaType.APPLICATION_JSON)
public static List<Info> getThreadInfo() {
ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
ImmutableList.Builder<Info> builder = ImmutableList.builder();
for (ThreadInfo info : mbean.getThreadInfo(mbean.getAllThreadIds(), Integer.MAX_VALUE)) {
builder.add(new Info(info.getThreadId(), info.getThreadName(), info.getThreadState().name(), info.getLockOwnerId() == -1 ? null : info.getLockOwnerId(), toStackTrace(info.getStackTrace())));
}
return Ordering.from(byName()).sortedCopy(builder.build());
}
Aggregations