Search in sources :

Example 6 with ThreadMXBean

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+\\]"));
    }
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo) Matchers.containsString(org.hamcrest.Matchers.containsString) HashSet(java.util.HashSet)

Example 7 with ThreadMXBean

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());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Random(java.util.Random) ArrayList(java.util.ArrayList) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) HashSet(java.util.HashSet) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ESTestCase(org.elasticsearch.test.ESTestCase) ManagementFactory(java.lang.management.ManagementFactory) Before(org.junit.Before) CyclicBarrier(java.util.concurrent.CyclicBarrier) Matchers.empty(org.hamcrest.Matchers.empty) Set(java.util.Set) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ThreadMXBean(java.lang.management.ThreadMXBean) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Matchers.is(org.hamcrest.Matchers.is) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Random(java.util.Random) ExecutionException(java.util.concurrent.ExecutionException) ThreadMXBean(java.lang.management.ThreadMXBean) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CountDownLatch(java.util.concurrent.CountDownLatch) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 8 with ThreadMXBean

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();
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) MemoryUsage(java.lang.management.MemoryUsage)

Example 9 with ThreadMXBean

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();
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo)

Example 10 with ThreadMXBean

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());
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo) ImmutableList(com.google.common.collect.ImmutableList) ThreadInfo(java.lang.management.ThreadInfo) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

ThreadMXBean (java.lang.management.ThreadMXBean)87 ThreadInfo (java.lang.management.ThreadInfo)43 HashMap (java.util.HashMap)8 MemoryMXBean (java.lang.management.MemoryMXBean)7 RuntimeMXBean (java.lang.management.RuntimeMXBean)7 IOException (java.io.IOException)6 OperatingSystemMXBean (java.lang.management.OperatingSystemMXBean)6 ArrayList (java.util.ArrayList)6 File (java.io.File)5 HashSet (java.util.HashSet)5 Map (java.util.Map)5 ClassLoadingMXBean (java.lang.management.ClassLoadingMXBean)4 GarbageCollectorMXBean (java.lang.management.GarbageCollectorMXBean)4 MemoryUsage (java.lang.management.MemoryUsage)4 Date (java.util.Date)4 MonitorInfo (java.lang.management.MonitorInfo)3 Properties (java.util.Properties)3 Test (org.junit.Test)3 SnmpStatusException (com.sun.jmx.snmp.SnmpStatusException)2 FileOutputStream (java.io.FileOutputStream)2