下面列出了java.util.concurrent.ThreadFactory#newThread ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
MessageBatcher(
int bufferSize,
int maxBatchSize,
EnqueueBehaviour enqueueBehaviour,
Function<List<MESSAGE>, List<RESPONSE>> batchHandler,
ThreadFactory threadFactory) {
if (bufferSize < maxBatchSize) {
throw new IllegalArgumentException("maxBatchSize must be less than or equal to bufferSize");
}
this.queue = new LinkedBlockingQueue<>(bufferSize);
this.maxBatchSize = maxBatchSize;
this.batchHandler = batchHandler;
this.enqueueBehaviour = enqueueBehaviour;
thread = threadFactory.newThread(this::processMessages);
thread.start();
}
/**
* Get a named {@link ThreadFactory} that just builds daemon threads.
* @param prefix name prefix for all threads created from the factory
* @return a thread factory that creates named, daemon threads with
* the supplied exception handler and normal priority
*/
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
return new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = namedFactory.newThread(r);
if (!t.isDaemon()) {
t.setDaemon(true);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
};
}
public ThreadPoolEventTarget(
final ThreadFactory wrappedFactory, final ThreadInitializer threadInitializer) {
int poolSize = 1;
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
executor =
new ThreadPoolExecutor(
poolSize,
poolSize,
3,
TimeUnit.SECONDS,
queue,
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = wrappedFactory.newThread(r);
threadInitializer.setName(thread, "FirebaseDatabaseEventTarget");
threadInitializer.setDaemon(thread, true);
// TODO: should we set an uncaught exception handler here? Probably want to let
// exceptions happen...
return thread;
}
});
}
@Test
public void buildThreadFactory() {
Runnable testRunnable = new Runnable() {
@Override
public void run() {
}
};
// 测试name格式
ThreadFactory threadFactory = ThreadPoolUtil.buildThreadFactory("example");
Thread thread = threadFactory.newThread(testRunnable);
assertThat(thread.getName()).isEqualTo("example-0");
assertThat(thread.isDaemon()).isFalse();
// 测试daemon属性设置
threadFactory = ThreadPoolUtil.buildThreadFactory("example", true);
Thread thread2 = threadFactory.newThread(testRunnable);
assertThat(thread.getName()).isEqualTo("example-0");
assertThat(thread2.isDaemon()).isTrue();
}
static ThreadFactory createQpidByteBufferTrackingThreadFactory(ThreadFactory factory)
{
return r -> factory.newThread(() -> {
try
{
r.run();
}
finally
{
final SingleQpidByteBuffer cachedThreadLocalBuffer = _cachedBuffer.get();
if (cachedThreadLocalBuffer != null)
{
cachedThreadLocalBuffer.dispose();
_cachedBuffer.remove();
}
}
});
}
@Test
public void buildThreadFactory() {
Runnable testRunnable = new Runnable() {
@Override
public void run() {
}
};
// 测试name格式
ThreadFactory threadFactory = ThreadPoolUtil.buildThreadFactory("example");
Thread thread = threadFactory.newThread(testRunnable);
assertThat(thread.getName()).isEqualTo("example-0");
assertThat(thread.isDaemon()).isFalse();
// 测试daemon属性设置
threadFactory = ThreadPoolUtil.buildThreadFactory("example", true);
Thread thread2 = threadFactory.newThread(testRunnable);
assertThat(thread.getName()).isEqualTo("example-0");
assertThat(thread2.isDaemon()).isTrue();
}
static void threadFactory() {
ThreadFactory factory = new ThreadFactory() {
int count = 0;
@Override
public Thread newThread(Runnable r) {
count ++;
return new Thread(r, "Thread-" + count);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " started!");
}
};
Thread thread = factory.newThread(runnable);
thread.start();
Thread thread1 = factory.newThread(runnable);
thread1.start();
}
public BulkProcessor(
Time time,
BulkClient<R, B> bulkClient,
int maxBufferedRecords,
int maxInFlightRequests,
int batchSize,
long lingerMs,
int maxRetries,
long retryBackoffMs
) {
this.time = time;
this.bulkClient = bulkClient;
this.maxBufferedRecords = maxBufferedRecords;
this.batchSize = batchSize;
this.lingerMs = lingerMs;
this.maxRetries = maxRetries;
this.retryBackoffMs = retryBackoffMs;
unsentRecords = new ArrayDeque<>(maxBufferedRecords);
final ThreadFactory threadFactory = makeThreadFactory();
farmer = threadFactory.newThread(farmerTask());
executor = Executors.newFixedThreadPool(maxInFlightRequests, threadFactory);
}
protected ThreadFactory makeConfigured(ThreadFactory origin,
Boolean isDaemon,
Integer priority,
UncaughtExceptionHandler uncaughtExceptionHandler) {
if (null != isDaemon && null == priority && null == uncaughtExceptionHandler) {
return origin;
} else {
return r -> {
Thread t = origin.newThread(r);
if (null != priority && priority != t.getPriority()) {
t.setPriority(priority);
}
if (null != isDaemon && isDaemon != t.isDaemon()) {
t.setDaemon(isDaemon);
}
if (null != uncaughtExceptionHandler) {
t.setUncaughtExceptionHandler(uncaughtExceptionHandler);
}
return t;
};
}
}
protected ThreadFactory makeContextual(ThreadFactory origin,
ClassLoader contextClassLoader,
Function<? super Runnable, ? extends Runnable> wrapper) {
if (null == contextClassLoader) {
return origin;
} else {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Fail fast
sm.checkPermission(new RuntimePermission("setContextClassLoader"));
}
return r -> {
Runnable contextualRunnable = () -> {
Thread.currentThread().setContextClassLoader(contextClassLoader);
r.run();
};
return origin.newThread(wrapper.apply(contextualRunnable));
};
}
}
/**
* Starts the Cleaner implementation.
* Ensure this is the CleanerImpl for the Cleaner.
* When started waits for Cleanables to be queued.
* @param cleaner the cleaner
* @param threadFactory the thread factory
*/
public void start(Cleaner cleaner, ThreadFactory threadFactory) {
if (getCleanerImpl(cleaner) != this) {
throw new AssertionError("wrong cleaner");
}
// schedule a nop cleaning action for the cleaner, so the associated thread
// will continue to run at least until the cleaner is reclaimable.
new CleanerCleanable(cleaner);
if (threadFactory == null) {
threadFactory = CleanerImpl.InnocuousThreadFactory.factory();
}
// now that there's at least one cleaning action, for the cleaner,
// we can start the associated thread, which runs until
// all cleaning actions have been run.
Thread thread = threadFactory.newThread(this);
thread.setDaemon(true);
thread.start();
}
/**
* Starts the Cleaner implementation.
* Ensure this is the CleanerImpl for the Cleaner.
* When started waits for Cleanables to be queued.
* @param cleaner the cleaner
* @param threadFactory the thread factory
*/
public void start(Cleaner cleaner, ThreadFactory threadFactory) {
if (getCleanerImpl(cleaner) != this) {
throw new AssertionError("wrong cleaner");
}
// schedule a nop cleaning action for the cleaner, so the associated thread
// will continue to run at least until the cleaner is reclaimable.
new CleanerCleanable(cleaner);
if (threadFactory == null) {
threadFactory = CleanerImpl.InnocuousThreadFactory.factory();
}
// now that there's at least one cleaning action, for the cleaner,
// we can start the associated thread, which runs until
// all cleaning actions have been run.
Thread thread = threadFactory.newThread(this);
thread.setDaemon(true);
thread.start();
}
/**
* Creates a new timer.
*
* @param threadFactory a {@link ThreadFactory} that creates a
* background {@link Thread} which is dedicated to
* {@link TimerTask} execution.
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @param ticksPerWheel the size of the wheel
* @param maxPendingTimeouts The maximum number of pending timeouts after which call to
* {@code newTimeout} will result in
* {@link RejectedExecutionException}
* being thrown. No maximum pending timeouts limit is assumed if
* this value is 0 or negative.
* @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null}
* @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0
*/
public HashedWheelTimer(ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel,
long maxPendingTimeouts) {
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
}
if (unit == null) {
throw new NullPointerException("unit");
}
if (tickDuration <= 0) {
throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
}
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
// Normalize ticksPerWheel to power of two and initialize the wheel.
wheel = createWheel(ticksPerWheel);
mask = wheel.length - 1;
// Convert tickDuration to nanos.
this.tickDuration = unit.toNanos(tickDuration);
// Prevent overflow.
if (this.tickDuration >= Long.MAX_VALUE / wheel.length) {
throw new IllegalArgumentException(String.format(
"tickDuration: %d (expected: 0 < tickDuration in nanos < %d", tickDuration, Long.MAX_VALUE
/ wheel.length));
}
workerThread = threadFactory.newThread(worker);
this.maxPendingTimeouts = maxPendingTimeouts;
if (instanceCounter.incrementAndGet() > INSTANCE_COUNT_LIMIT
&& warnedTooManyInstances.compareAndSet(false, true)) {
reportTooManyInstances();
}
}
public FileTailer(FileChangeListener fileChangeListener, int bufferSize, int maxLinesPerCycle, long idleTimeMs, ThreadFactory processingThreadFactory) {
this.tailableFiles = new CopyOnWriteArrayList<>();
this.fileChangeListener = fileChangeListener;
this.buffer = ByteBuffer.allocate(bufferSize);
this.maxLinesPerCycle = maxLinesPerCycle;
this.idleTimeMs = idleTimeMs;
this.processingThread = processingThreadFactory.newThread(this);
}
private void verifyGetNamedThreadFactory(String threadFactorName) {
final ThreadFactory threadFactory = ExecutorUtils.getNamedThreadFactory(threadFactorName);
Thread thread;
for (int i = 0; i < 2; i++) {
thread = threadFactory.newThread(mock(Runnable.class));
// Thread identifier starts from 1
assertEquals(threadFactorName + (i + 1), thread.getName());
}
}
private Thread waitToExit(ThreadFactory threadFactory, final Provider<? extends SafeExit> provider) {
return threadFactory.newThread(new Runnable() {
@Override
public void run() {
SafeExit safeExit;
try {
safeExit = provider.get();
} catch (Exception ex){
// ignore since this means no instance wasn't running on this node.
return;
}
safeExit.waitToExit();
}
});
}
public HashedWheelTimer(ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, Processor processor) {
this.processor = processor;
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
}
if (unit == null) {
throw new NullPointerException("unit");
}
if (tickDuration <= 0) {
throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
}
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
// Normalize ticksPerWheel to power of two and initialize the wheel.
wheel = createWheel(ticksPerWheel);
mask = wheel.length - 1;
// Convert tickDuration to nanos.
this.tickDuration = unit.toNanos(tickDuration);
// Prevent overflow.
if (this.tickDuration >= Long.MAX_VALUE / wheel.length) {
throw new IllegalArgumentException(String.format(
"tickDuration: %d (expected: 0 < tickDuration in nanos < %d",
tickDuration, Long.MAX_VALUE / wheel.length));
}
workerThread = threadFactory.newThread(worker);
}
@Provides @Singleton
NamedThreadFactory namedThreadFactory(ThreadFactory factory) {
return (name, code) -> {
final Thread thread = factory.newThread(code);
thread.setName(name);
return thread;
};
}
void test(final Class<?> exceptionClass,
final ThreadFactory failingThreadFactory)
throws Throwable {
ThreadFactory flakyThreadFactory = new ThreadFactory() {
int seq = 0;
public Thread newThread(Runnable r) {
if (seq++ < 4)
return new Thread(r);
else
return failingThreadFactory.newThread(r);
}};
ThreadPoolExecutor pool =
new ThreadPoolExecutor(10, 10,
0L, TimeUnit.SECONDS,
new LinkedBlockingQueue(),
flakyThreadFactory);
try {
for (int i = 0; i < 8; i++)
pool.submit(new Runnable() { public void run() {} });
check(exceptionClass == null);
} catch (Throwable t) {
/* t.printStackTrace(); */
check(exceptionClass.isInstance(t));
}
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
private static ThreadFactory build(ThreadFactoryBuilder builder) {
final String nameFormat = builder.nameFormat;
final Boolean daemon = builder.daemon;
final Integer priority = builder.priority;
final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
final ThreadFactory backingThreadFactory = (builder.backingThreadFactory != null) ? builder.backingThreadFactory : Executors.defaultThreadFactory();
final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
return new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = backingThreadFactory.newThread(runnable);
if (nameFormat != null) {
thread.setName(format(nameFormat, count.getAndIncrement()));
}
if (daemon != null) {
thread.setDaemon(daemon);
}
if (priority != null) {
thread.setPriority(priority);
}
if (uncaughtExceptionHandler != null) {
thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
}
return thread;
}
};
}