use of java.lang.management.ThreadMXBean in project cassandra by apache.
the class ToolsTester method assertNoUnexpectedThreadsStarted.
public void assertNoUnexpectedThreadsStarted(String[] expectedThreadNames, String[] optionalThreadNames) {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
Set<String> initial = initialThreads.stream().map(ThreadInfo::getThreadName).collect(Collectors.toSet());
Set<String> current = Arrays.stream(threads.getThreadInfo(threads.getAllThreadIds())).map(ThreadInfo::getThreadName).collect(Collectors.toSet());
List<Pattern> expected = expectedThreadNames != null ? Arrays.stream(expectedThreadNames).map(Pattern::compile).collect(Collectors.toList()) : Collections.emptyList();
List<Pattern> optional = optionalThreadNames != null ? Arrays.stream(optionalThreadNames).map(Pattern::compile).collect(Collectors.toList()) : Collections.emptyList();
current.removeAll(initial);
List<Pattern> notPresent = expected.stream().filter(threadNamePattern -> !current.stream().anyMatch(threadName -> threadNamePattern.matcher(threadName).matches())).collect(Collectors.toList());
Set<String> remain = current.stream().filter(threadName -> expected.stream().anyMatch(pattern -> pattern.matcher(threadName).matches())).filter(threadName -> optional.stream().anyMatch(pattern -> pattern.matcher(threadName).matches())).collect(Collectors.toSet());
if (!current.isEmpty())
System.err.println("Unexpected thread names: " + remain);
if (!notPresent.isEmpty())
System.err.println("Mandatory thread missing: " + notPresent);
assertTrue("Wrong thread status", remain.isEmpty() && notPresent.isEmpty());
}
use of java.lang.management.ThreadMXBean in project flink by apache.
the class TaskExecutorMetricsInitializer method instantiateThreadMetrics.
private static void instantiateThreadMetrics(MetricGroup metrics) {
final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
metrics.<Integer, Gauge<Integer>>gauge("Count", new Gauge<Integer>() {
@Override
public Integer getValue() {
return mxBean.getThreadCount();
}
});
}
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 hbase by apache.
the class GenericTestUtils method assertNoThreadsMatching.
/**
* 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()));
}
}
}
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());
}
Aggregations