You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2019/01/23 01:22:06 UTC
[geode] branch develop updated: GEODE-6301: Add call stack support
to ExecutorServiceRule
This is an automated email from the ASF dual-hosted git repository.
klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new f81d185 GEODE-6301: Add call stack support to ExecutorServiceRule
f81d185 is described below
commit f81d1854d33d31218d5131aa69b6c7c62c536333
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Fri Jan 18 14:53:41 2019 -0800
GEODE-6301: Add call stack support to ExecutorServiceRule
---
.../rules/ExecutorServiceRuleIntegrationTest.java | 10 +-
.../test/junit/rules/ExecutorServiceRule.java | 104 ++++++++++++++++++++-
.../rules/ExecutorServiceRuleGetThreadsTest.java | 100 ++++++++++++++++++++
3 files changed, 208 insertions(+), 6 deletions(-)
diff --git a/geode-junit/src/integrationTest/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleIntegrationTest.java b/geode-junit/src/integrationTest/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleIntegrationTest.java
index a49a7e1..15f3c31 100644
--- a/geode-junit/src/integrationTest/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleIntegrationTest.java
+++ b/geode-junit/src/integrationTest/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleIntegrationTest.java
@@ -40,14 +40,14 @@ public class ExecutorServiceRuleIntegrationTest {
private static Awaits.Invocations invocations;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
hangLatch = new CountDownLatch(1);
terminateLatch = new CountDownLatch(1);
invocations = mock(Awaits.Invocations.class);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
invocations = null;
while (hangLatch != null && hangLatch.getCount() > 0) {
@@ -92,17 +92,17 @@ public class ExecutorServiceRuleIntegrationTest {
ExecutorServiceRule.builder().awaitTermination(2, SECONDS).build();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
executorService = executorServiceRule.getExecutorService();
}
@After
- public void after() throws Exception {
+ public void after() {
invocations.afterTest();
}
@Test
- public void doTest() throws Exception {
+ public void doTest() {
executorServiceRule.runAsync(() -> {
try {
hangLatch.await(1, SECONDS);
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/ExecutorServiceRule.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/ExecutorServiceRule.java
index f79d874..d152bdf 100644
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/ExecutorServiceRule.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/ExecutorServiceRule.java
@@ -14,13 +14,21 @@
*/
package org.apache.geode.test.junit.rules;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.lang.management.ThreadMXBean;
+import java.lang.ref.WeakReference;
+import java.util.HashSet;
+import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
@@ -86,6 +94,7 @@ public class ExecutorServiceRule extends SerializableExternalResource {
protected final boolean useShutdown;
protected final boolean useShutdownNow;
+ protected transient volatile DedicatedThreadFactory threadFactory;
protected transient volatile ExecutorService executor;
/**
@@ -119,7 +128,8 @@ public class ExecutorServiceRule extends SerializableExternalResource {
@Override
public void before() {
- executor = Executors.newCachedThreadPool();
+ threadFactory = new DedicatedThreadFactory();
+ executor = Executors.newCachedThreadPool(threadFactory);
}
@Override
@@ -236,6 +246,98 @@ public class ExecutorServiceRule extends SerializableExternalResource {
return CompletableFuture.supplyAsync(supplier, executor);
}
+ /**
+ * Returns the {@code Thread}s that are directly in the {@code ExecutorService}'s
+ * {@code ThreadGroup} excluding subgroups.
+ */
+ public Set<Thread> getThreads() {
+ return threadFactory.getThreads();
+ }
+
+ /**
+ * Returns an array of {@code Thread Ids} that are directly in the {@code ExecutorService}'s
+ * {@code ThreadGroup} excluding subgroups. {@code long[]} is returned to facilitate using JDK
+ * APIs such as {@code ThreadMXBean#getThreadInfo(long[], int)}.
+ */
+ public long[] getThreadIds() {
+ Set<Thread> threads = getThreads();
+ long[] threadIds = new long[threads.size()];
+
+ int i = 0;
+ for (Thread thread : threads) {
+ threadIds[i++] = thread.getId();
+ }
+
+ return threadIds;
+ }
+
+ /**
+ * Returns formatted call stacks of the {@code Thread}s that are directly in the
+ * {@code ExecutorService}'s {@code ThreadGroup} excluding subgroups.
+ */
+ public String dumpThreads() {
+ StringBuilder dump = new StringBuilder();
+ ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(getThreadIds(), 100);
+ for (ThreadInfo threadInfo : threadInfos) {
+ dump.append('"');
+ dump.append(threadInfo.getThreadName());
+ dump.append("\" ");
+ final Thread.State state = threadInfo.getThreadState();
+ dump.append("\n java.lang.Thread.State: ");
+ dump.append(state);
+ final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
+ for (final StackTraceElement stackTraceElement : stackTraceElements) {
+ dump.append("\n at ");
+ dump.append(stackTraceElement);
+ }
+ dump.append("\n\n");
+ }
+ return dump.toString();
+ }
+
+ /**
+ * Modified version of {@code java.util.concurrent.Executors$DefaultThreadFactory} that uses
+ * a {@code Set<WeakReference<Thread>>} to track the {@code Thread}s in the factory's
+ * {@code ThreadGroup} excluding subgroups.
+ */
+ static class DedicatedThreadFactory implements ThreadFactory {
+ private static final AtomicInteger poolNumber = new AtomicInteger(1);
+ private final ThreadGroup group;
+ private final AtomicInteger threadNumber = new AtomicInteger(1);
+ private final String namePrefix;
+ private final Set<WeakReference<Thread>> directThreads = new HashSet<>();
+
+ DedicatedThreadFactory() {
+ group = new ThreadGroup(ExecutorServiceRule.class.getSimpleName() + "-ThreadGroup");
+ namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
+ }
+
+ @Override
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
+ if (t.isDaemon()) {
+ t.setDaemon(false);
+ }
+ if (t.getPriority() != Thread.NORM_PRIORITY) {
+ t.setPriority(Thread.NORM_PRIORITY);
+ }
+ directThreads.add(new WeakReference<>(t));
+ return t;
+ }
+
+ Set<Thread> getThreads() {
+ Set<Thread> value = new HashSet<>();
+ for (WeakReference<Thread> reference : directThreads) {
+ Thread thread = reference.get();
+ if (thread != null) {
+ value.add(thread);
+ }
+ }
+ return value;
+ }
+ }
+
public static class Builder {
protected boolean enableAwaitTermination;
diff --git a/geode-junit/src/test/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleGetThreadsTest.java b/geode-junit/src/test/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleGetThreadsTest.java
new file mode 100644
index 0000000..3e12a5e
--- /dev/null
+++ b/geode-junit/src/test/java/org/apache/geode/test/junit/rules/ExecutorServiceRuleGetThreadsTest.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.test.junit.rules;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
+import static org.apache.geode.test.awaitility.GeodeAwaitility.getTimeout;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.After;
+import org.junit.Rule;
+import org.junit.Test;
+
+/**
+ * Unit tests for {@link ExecutorServiceRule#getThreads()}.
+ */
+public class ExecutorServiceRuleGetThreadsTest {
+
+ private static final long TIMEOUT_MILLIS = getTimeout().getValueInMS();
+
+ private final CountDownLatch terminateLatch = new CountDownLatch(1);
+ private final AtomicBoolean submittedChildren = new AtomicBoolean();
+
+ private volatile ExecutorService executorService;
+
+ @Rule
+ public ExecutorServiceRule executorServiceRule = new ExecutorServiceRule();
+
+ @After
+ public void tearDown() {
+ terminateLatch.countDown();
+ }
+
+ @Test
+ public void noThreads() {
+ assertThat(executorServiceRule.getThreads()).isEmpty();
+ }
+
+ @Test
+ public void oneThread() {
+ executorServiceRule.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+
+ assertThat(executorServiceRule.getThreads()).hasSize(1);
+ }
+
+ @Test
+ public void twoThreads() {
+ executorServiceRule.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+ executorServiceRule.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+
+ assertThat(executorServiceRule.getThreads()).hasSize(2);
+ }
+
+ @Test
+ public void childExecutorService() {
+ executorServiceRule.submit(() -> {
+ executorService = Executors.newCachedThreadPool();
+ executorService.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+ executorService.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+ submittedChildren.set(true);
+ });
+
+ await().untilTrue(submittedChildren);
+
+ assertThat(executorServiceRule.getThreads().size()).isLessThanOrEqualTo(1);
+ }
+
+ @Test
+ public void getThreadIds() {
+ executorServiceRule.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+ executorServiceRule.submit(() -> terminateLatch.await(TIMEOUT_MILLIS, MILLISECONDS));
+
+ long[] threadIds = executorServiceRule.getThreadIds();
+
+ assertThat(threadIds).hasSize(2);
+
+ Set<Thread> threads = executorServiceRule.getThreads();
+ for (Thread thread : threads) {
+ assertThat(threadIds).contains(thread.getId());
+ }
+ }
+}