You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2023/09/28 21:17:25 UTC
[groovy] 01/03: GROOVY-11183: Add `allThreads` method to `Thread`
This is an automated email from the ASF dual-hosted git repository.
sunlan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 1273fe3e7ce5d02e732576aa1580441595b5df6c
Author: Daniel Sun <su...@apache.org>
AuthorDate: Thu Sep 28 01:30:37 2023 +0800
GROOVY-11183: Add `allThreads` method to `Thread`
---
.../groovy/runtime/DefaultGroovyStaticMethods.java | 25 ++++++++++++++++++++++
.../runtime/DefaultGroovyStaticMethodsTest.groovy | 4 ++++
2 files changed, 29 insertions(+)
diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java
index 71f7883eab..52181bb357 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java
@@ -30,7 +30,9 @@ import java.lang.management.ThreadMXBean;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
+import java.util.List;
import java.util.Locale;
+import java.util.Objects;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
@@ -115,6 +117,29 @@ public class DefaultGroovyStaticMethods {
.collect(Collectors.joining(""));
}
+ /**
+ * Get all threads
+ *
+ * @param self placeholder variable used by Groovy categories; ignored for default static methods
+ * @return all threads
+ * @since 4.0.16
+ */
+ public static List<Thread> allThreads(Thread self) {
+ ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
+ for (ThreadGroup parentGroup; (parentGroup = rootGroup.getParent()) != null; ) {
+ rootGroup = parentGroup;
+ }
+
+ Thread[] threads = new Thread[rootGroup.activeCount()];
+ while (rootGroup.enumerate(threads, true) == threads.length) {
+ threads = new Thread[threads.length * 2];
+ }
+
+ return Arrays.stream(threads)
+ .filter(Objects::nonNull)
+ .collect(Collectors.toUnmodifiableList());
+ }
+
/**
* Get the last hidden matcher that the system used to do a match.
*
diff --git a/src/test/org/codehaus/groovy/runtime/DefaultGroovyStaticMethodsTest.groovy b/src/test/org/codehaus/groovy/runtime/DefaultGroovyStaticMethodsTest.groovy
index 4a25981cdd..5f6c305b36 100644
--- a/src/test/org/codehaus/groovy/runtime/DefaultGroovyStaticMethodsTest.groovy
+++ b/src/test/org/codehaus/groovy/runtime/DefaultGroovyStaticMethodsTest.groovy
@@ -35,4 +35,8 @@ class DefaultGroovyStaticMethodsTest extends GroovyTestCase {
void testDumpAll() {
assert Thread.dumpAll().contains("dumpAll")
}
+
+ void testAllThreads() {
+ assert Thread.allThreads().stream().anyMatch(t -> 'Finalizer' == t.name)
+ }
}