Skip to content

Commit

Permalink
optimize: enable NamedThreadFactory to get ThreadGroup from the Secur…
Browse files Browse the repository at this point in the history
…ityManager or Current thread (apache#3310)
  • Loading branch information
jxlgzwh committed Dec 6, 2020
1 parent 5a85c5c commit 10c03d0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
*/
public class NamedThreadFactory implements ThreadFactory {
private final static Map<String, AtomicInteger> PREFIX_COUNTER = new ConcurrentHashMap<>();

private final ThreadGroup group;
private final AtomicInteger counter = new AtomicInteger(0);
private final String prefix;
private final int totalSize;
Expand All @@ -47,6 +47,8 @@ public class NamedThreadFactory implements ThreadFactory {
public NamedThreadFactory(String prefix, int totalSize, boolean makeDaemons) {
int prefixCounter = CollectionUtils.computeIfAbsent(PREFIX_COUNTER, prefix, key -> new AtomicInteger(0))
.incrementAndGet();
SecurityManager securityManager = System.getSecurityManager();
group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.prefix = prefix + "_" + prefixCounter;
this.makeDaemons = makeDaemons;
this.totalSize = totalSize;
Expand Down Expand Up @@ -78,7 +80,7 @@ public Thread newThread(Runnable r) {
if (totalSize > 1) {
name += "_" + totalSize;
}
Thread thread = new FastThreadLocalThread(r, name);
Thread thread = new FastThreadLocalThread(group, r, name);

thread.setDaemon(makeDaemons);
if (thread.getPriority() != Thread.NORM_PRIORITY) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,12 @@ public void testThreadNameHasCounterWithPrefixCounter() {
.isEqualTo(thread.getName());
}
}

@Test
public void testNamedThreadFactoryWithSecurityManager() {
NamedThreadFactory factory = new NamedThreadFactory("testThreadGroup", true);
Thread thread = factory.newThread(() -> {});
assertThat(thread.getThreadGroup()).isNotNull();
}

}

0 comments on commit 10c03d0

Please sign in to comment.