Java Code Examples for java.util.concurrent.ThreadFactory#newThread()
The following examples show how to use
java.util.concurrent.ThreadFactory#newThread() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CleanerImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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(); }
Example 2
Source File: S3AFileSystem.java From hadoop with Apache License 2.0 | 6 votes |
/** * 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; } }; }
Example 3
Source File: CleanerImpl.java From Bytecoder with Apache License 2.0 | 6 votes |
/** * 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(); }
Example 4
Source File: ThreadFactoryBuilder.java From tascalate-concurrent with Apache License 2.0 | 6 votes |
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)); }; } }
Example 5
Source File: ThreadPoolEventTarget.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
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; } }); }
Example 6
Source File: ThreadFactoryBuilder.java From tascalate-concurrent with Apache License 2.0 | 6 votes |
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; }; } }
Example 7
Source File: ThreadPoolUtilTest.java From vjtools with Apache License 2.0 | 6 votes |
@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(); }
Example 8
Source File: QpidByteBufferFactory.java From qpid-broker-j with Apache License 2.0 | 6 votes |
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(); } } }); }
Example 9
Source File: MessageBatcher.java From data-highway with Apache License 2.0 | 6 votes |
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(); }
Example 10
Source File: ThreadPoolUtilTest.java From vjtools with Apache License 2.0 | 6 votes |
@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(); }
Example 11
Source File: Main.java From PlusDemo with Apache License 2.0 | 6 votes |
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(); }
Example 12
Source File: BulkProcessor.java From jkes with Apache License 2.0 | 6 votes |
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); }
Example 13
Source File: HashedWheelTimer.java From qmq with Apache License 2.0 | 5 votes |
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); }
Example 14
Source File: FlakyThreadFactory.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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)); }
Example 15
Source File: UtilCoreManifest.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
@Provides @Singleton NamedThreadFactory namedThreadFactory(ThreadFactory factory) { return (name, code) -> { final Thread thread = factory.newThread(code); thread.setName(name); return thread; }; }
Example 16
Source File: NodeRegistration.java From dremio-oss with Apache License 2.0 | 5 votes |
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(); } }); }
Example 17
Source File: ExecutorUtilsTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
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()); } }
Example 18
Source File: FileTailer.java From apm-agent-java with Apache License 2.0 | 5 votes |
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); }
Example 19
Source File: HashedWheelTimer.java From sofa-jraft with Apache License 2.0 | 5 votes |
/** * 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(); } }
Example 20
Source File: ThreadFactoryBuilder.java From ns4_gear_watchdog with Apache License 2.0 | votes |
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; } }; }