blob: 70302d5fbdcb11e3b3a6dc2e92e307d6a1c53f40 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author baldersheim
*/
public class ThreadFactoryFactory {
static public synchronized ThreadFactory getThreadFactory(String name) {
PooledFactory p = factory.get(name);
if (p == null) {
p = new PooledFactory(name);
factory.put(name, p);
}
return p.getFactory(false);
}
static public synchronized ThreadFactory getDaemonThreadFactory(String name) {
PooledFactory p = factory.get(name);
if (p == null) {
p = new PooledFactory(name);
factory.put(name, p);
}
return p.getFactory(true);
}
private static class PooledFactory {
private static class Factory implements ThreadFactory {
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
final boolean isDaemon;
Factory(final String name, boolean isDaemon) {
this.isDaemon = isDaemon;
final SecurityManager s = System.getSecurityManager();
group = (s != null)
? s.getThreadGroup()
: Thread.currentThread().getThreadGroup();
namePrefix = name;
}
@Override
public Thread newThread(final Runnable r) {
final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
if (t.isDaemon() != isDaemon) {
t.setDaemon(isDaemon);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
PooledFactory(String name) {
this.name = name;
}
ThreadFactory getFactory(boolean isDaemon) {
return new Factory(name + "-" + poolId.getAndIncrement() + "-thread-", isDaemon);
}
private final String name;
private final AtomicInteger poolId = new AtomicInteger(1);
}
static private Map<String, PooledFactory> factory = new HashMap<>();
}
|