For IntelliJ IDEA,
Android Studio or Eclipse



private void myMethod () {ThreadPoolExecutor t =
TimeUnit unit;new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue)
(ThreadPoolExecutor) Executors.newFixedThreadPool(int1)
TimeUnit unit;new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory)
- Smart code suggestions by Codota
}
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RejectedExecutionException("Got Interrupted while adding to the Queue", e); } } }
@Override public void run() { for (;;) { long c = m2.getCount(); try { Thread.sleep(2000L); } catch (InterruptedException e) { continue; } System.out.println("tps:" + (m2.getCount() - c) / 2); System.out.println(" x:" + m2.getX().getQueue().size()); System.out.println(" y:" + m2.getY().size()); System.out.println("=============="); } } }.start();
/** * Return status information about the underlying threadpool. */ @Override public String toString() { return String.format("active: %d/%d submitted: %d completed: %d input_q: %d output_q: %d idle_q: %d", threadPool.getActiveCount(), threadPool.getPoolSize(), threadPool.getTaskCount(), threadPool.getCompletedTaskCount(), threadPool.getQueue().size(), outputQueue.size(), idleProcessors.size()); }
public DiffApplier(int diffParallelism, FileSource source, FileDestination destination) { Preconditions.checkNotNull(source); Preconditions.checkNotNull(destination); this.diffsFailedPaths = new ConcurrentSkipListSet<>(); this.refactoredPaths = Sets.newConcurrentHashSet(); this.source = source; this.destination = destination; this.completedFiles = new AtomicInteger(0); this.stopwatch = Stopwatch.createUnstarted(); // configure a bounded queue and a rejectedexecutionpolicy. // In this case CallerRuns may be appropriate. this.workerService = new ThreadPoolExecutor( 0, diffParallelism, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50), new ThreadPoolExecutor.CallerRunsPolicy()); }
@Override public void run() { for (;;) { long c = count.get(); try { Thread.sleep(5000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("count:" + (count.get() - c) / 5); System.out.println("active:" + executor.getActiveCount()); System.out.println("queue:" + executor.getQueue().size()); System.out.println("============================"); } } }.start();
/** * Wait for all threads to finish. * * @param destroyThreadpool -- if true, then destroy the worker threads * so that the main thread can shutdown. */ public void join(boolean destroyThreadpool) { // Make blocking calls to the last processes that are running if ( ! threadPool.isShutdown()) { try { for (int i = nThreads; i > 0; --i) { idleProcessors.take(); } if (destroyThreadpool) { threadPool.shutdown(); // Sanity check. The threadpool should be done after iterating over // the processors. threadPool.awaitTermination(10, TimeUnit.SECONDS); } else { // Repopulate the list of processors for (int i = 0; i < nThreads; ++i) { idleProcessors.put(i); } } } catch (InterruptedException e) { throw new RuntimeException(e); } } }
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { throw new RejectedExecutionException("Got Interrupted while adding to the Queue", e); } } }
protected ThreadPoolExecutor createThreadPool() { ThreadPoolExecutor threadPool=new ThreadPoolExecutor(0, max_pool, pool_thread_keep_alive, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>()); ThreadFactory factory=new ThreadFactory() { private final AtomicInteger thread_id=new AtomicInteger(1); public Thread newThread(final Runnable command) { return getThreadFactory().newThread(command, "StreamingStateTransfer-sender-" + thread_id.getAndIncrement()); } }; threadPool.setRejectedExecutionHandler(new ShutdownRejectedExecutionHandler(threadPool.getRejectedExecutionHandler())); threadPool.setThreadFactory(factory); return threadPool; }
@Override public boolean dispatch(final CallRunner task) throws IOException, InterruptedException { // Executors provide no offer, so make our own. int queued = queueSize.getAndIncrement(); if (maxQueueLength > 0 && queued >= maxQueueLength) { queueSize.decrementAndGet(); return false; } executor.execute(new FifoCallRunner(task){ @Override public void run() { task.setStatus(RpcServer.getStatus()); task.run(); queueSize.decrementAndGet(); } }); return true; }
/** * Stops the timer, cancelling all tasks * * @throws InterruptedException if interrupted while waiting for thread to return */ public void stop() { stopRunner(); List<Runnable> remaining_tasks=pool.shutdownNow(); for(Runnable task: remaining_tasks) { if(task instanceof Future) { Future future=(Future)task; future.cancel(true); } } pool.getQueue().clear(); try { pool.awaitTermination(Global.THREADPOOL_SHUTDOWN_WAIT_TIME, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { } }
/** * Stops the timer, cancelling all tasks */ public void stop() { stopRunner(); // we may need to do multiple iterations as the iterator works on a copy and tasks might have been added just // after the iterator() call returned while(!queue.isEmpty()) for(Task entry: queue) { entry.cancel(true); queue.remove(entry); } queue.clear(); List<Runnable> remaining_tasks=pool.shutdownNow(); for(Runnable task: remaining_tasks) { if(task instanceof Future) { Future future=(Future)task; future.cancel(true); } } pool.getQueue().clear(); try { pool.awaitTermination(Global.THREADPOOL_SHUTDOWN_WAIT_TIME, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { } // clears the threads list (https://issues.jboss.org/browse/JGRP-1971) if(timer_thread_factory instanceof LazyThreadFactory) ((LazyThreadFactory)timer_thread_factory).destroy(); }
this.waitQueue = new EvictingPriorityBlockingQueue<>(waitQueueComparator, waitQueueSize); this.clock = clock == null ? new MonotonicClock() : clock; this.threadPoolExecutor = new ThreadPoolExecutor(numExecutors, // core pool size new PreemptionQueueComparator()); this.enablePreemption = enablePreemption; this.numSlotsAvailable = new AtomicInteger(numExecutors); this.metrics = metrics; if (metrics != null) { metrics.setNumExecutorsAvailable(numSlotsAvailable.get());
assertEquals(0, pool.getPoolSize()); AtomicBoolean lock = new AtomicBoolean(true); AtomicInteger counter = new AtomicInteger(0); while (counter.get() < maxThreads && tries < maxTries) { LOG.info("Waiting for all event handlers to start..."); Thread.sleep(sleepInterval); assertEquals(maxThreads, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); lock.set(false); lock.notifyAll(); assertEquals(maxThreads * 2, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); lock.set(false); lock.notifyAll(); assertEquals(maxThreads, pool.getPoolSize());
/** * Stops the timer, cancelling all tasks * * @throws InterruptedException if interrupted while waiting for thread to return */ public void stop() { stopRunner(); java.util.List<Runnable> remaining_tasks=pool.shutdownNow(); for(Runnable task: remaining_tasks) { if(task instanceof Future) { Future future=(Future)task; future.cancel(true); } } pool.getQueue().clear(); try { pool.awaitTermination(Global.THREADPOOL_SHUTDOWN_WAIT_TIME, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { } for(Entry entry: tasks.values()) entry.cancel(); tasks.clear(); }
/** * Decrements the workerCount field of ctl. This is called only on * abrupt termination of a thread (see processWorkerExit). Other * decrements are performed within getTask. */ private void decrementWorkerCount() { do {} while (! compareAndDecrementWorkerCount(ctl.get())); }
Future<Boolean> acquire() { try { log.debug("Acquiring lock for shard={}.", shard); lockTaskCount.incrementAndGet(); return lockWorker.submit(acquirer()); } catch (RejectedExecutionException ex) { log.warn(String.format("Rejected lock execution: active:%d queue:%d shard:%d", lockWorker.getActiveCount(), lockWorker.getQueue().size(), shard)); return Futures.immediateFuture(false); } }
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (;;) { if (runStateAtLeast(ctl.get(), TERMINATED)) return true; if (nanos <= 0) return false; nanos = termination.awaitNanos(nanos); } } finally { mainLock.unlock(); } }
final void readCheck() { int currentCounter = next.getReceiveCounter(); int previousCounter = lastReceiveCounter.getAndSet(currentCounter); if (inReceive.get() || currentCounter != previousCounter) { if (LOG.isTraceEnabled()) { LOG.trace("A receive is in progress"); } return; } if (!commandReceived.get() && monitorStarted.get() && !ASYNC_TASKS.isTerminating()) { if (LOG.isDebugEnabled()) { LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); } ASYNC_TASKS.execute(new Runnable() { public void run() { if (protocolConverter != null) { protocolConverter.onTransportError(); } onException(new InactivityIOException("Channel was inactive for too (>" + readCheckTime + ") long: " + next.getRemoteAddress())); } ; }); } else { if (LOG.isTraceEnabled()) { LOG.trace("Message received since last read check, resetting flag: "); } } commandReceived.set(false); }
@Override public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { try { executor.getQueue().offer(r, 60, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RejectedExecutionException("Interrupted waiting for BrokerService.worker"); } throw new RejectedExecutionException("Timed Out while attempting to enqueue Task."); } });