Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize: enable NamedThreadFactory to get ThreadGroup from the SecurityManager or Current thread #3310

Merged
merged 2 commits into from
Dec 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,11 @@ public void testThreadNameHasCounterWithPrefixCounter() {
.isEqualTo(thread.getName());
}
}
@Test
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add an empty line before @test would be better.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add an empty line before @test would be better.

Thank you for your suggestion. I have dealt with it

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

}