List of usage examples for java.util.concurrent ThreadPoolExecutor setRejectedExecutionHandler
public void setRejectedExecutionHandler(RejectedExecutionHandler handler)
From source file:Main.java
@Deprecated public static ExecutorService newFixedThreadPool(int nThreads) { ThreadPoolExecutor exec = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(nThreads)); exec.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return exec;/* w ww .j a v a 2s. c o m*/ }
From source file:com.l2jfree.util.concurrent.L2ThreadPool.java
public static void initThreadPools(ThreadPoolInitializer initializer) throws Exception { if (!ArrayUtils.isEmpty(_scheduledPools) || !ArrayUtils.isEmpty(_instantPools) || !ArrayUtils.isEmpty(_longRunningPools)) throw new Exception("The thread pool has been already set!"); initializer.initThreadPool();//from ww w .j ava 2s . c o m _scheduledPools = initializer.getScheduledPools(); _instantPools = initializer.getInstantPools(); _longRunningPools = initializer.getLongRunningPools(); if (ArrayUtils.isEmpty(_scheduledPools)) { _log.info("No scheduled thread pool has been manually initialized, so initializing default one."); _scheduledPools = new ScheduledThreadPoolExecutor[] { new ScheduledThreadPoolExecutor( // // int corePoolSize 4) }; } if (ArrayUtils.isEmpty(_instantPools)) { _log.info("No instant thread pool has been manually initialized, so initializing default one."); _instantPools = new ThreadPoolExecutor[] { new ThreadPoolExecutor( // // int corePoolSize 0, // int maximumPoolSize Integer.MAX_VALUE, // long keepAliveTime 60L, // TimeUnit unit TimeUnit.SECONDS, // BlockingQueue<Runnable> workQueue new SynchronousQueue<Runnable>()) }; } if (ArrayUtils.isEmpty(_longRunningPools)) { _log.info("No long running thread pool has been manually initialized, so initializing default one."); _longRunningPools = new ThreadPoolExecutor[] { new ThreadPoolExecutor( // // int corePoolSize 0, // int maximumPoolSize Integer.MAX_VALUE, // long keepAliveTime 60L, // TimeUnit unit TimeUnit.SECONDS, // BlockingQueue<Runnable> workQueue new SynchronousQueue<Runnable>()) }; } for (ThreadPoolExecutor threadPool : getThreadPools()) { threadPool.setRejectedExecutionHandler(new L2RejectedExecutionHandler()); threadPool.prestartAllCoreThreads(); } scheduleAtFixedRate(new Runnable() { @Override public void run() { purge(); } }, 60000, 60000); _log.info("L2ThreadPool: Initialized with"); _log.info("\t... " + getPoolSize(_scheduledPools) + "/" + getMaximumPoolSize(_scheduledPools) + " scheduler,"); _log.info("\t... " + getPoolSize(_instantPools) + "/" + getMaximumPoolSize(_instantPools) + " instant,"); _log.info("\t... " + getPoolSize(_longRunningPools) + "/" + getMaximumPoolSize(_longRunningPools) + " long running thread(s)."); }
From source file:io.bitsquare.common.util.Utilities.java
public static ThreadPoolExecutor getThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTimeInSec) { final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(name).setDaemon(true).build(); ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec, TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory); executor.allowCoreThreadTimeOut(true); executor.setRejectedExecutionHandler((r, e) -> { log.debug("RejectedExecutionHandler called"); });//from www. j a va2 s. c om return executor; }
From source file:Main.java
public void runTest() throws Exception { ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); tp.setRejectedExecutionHandler( (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r)); Semaphore oneTaskDone = new Semaphore(0); tp.execute(() -> {/*ww w . j av a 2 s . c o m*/ System.out.println("Sleeping"); try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done sleeping"); oneTaskDone.release(); }); tp.execute(new Runnable() { @Override public void run() { System.out.println("Never happends"); } @Override public String toString() { return "Rejected Runnable"; } }); oneTaskDone.acquire(); tp.execute(() -> System.out.println("Running")); tp.shutdown(); tp.awaitTermination(100, TimeUnit.MILLISECONDS); System.out.println("Finished"); }
From source file:co.paralleluniverse.galaxy.netty.AbstractTcpServer.java
private void configureThreadPool(String name, ThreadPoolExecutor executor) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); executor.setThreadFactory(/*from w w w. ja va2 s .co m*/ new ThreadFactoryBuilder().setNameFormat(name + "-%d").setThreadFactory(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new CommThread(r); } }).build()); ThreadPoolExecutorMonitor.register(name, executor); }
From source file:com.xerox.amazonws.sdb.Domain.java
/** * Gets attributes of given items. This method threads off the get requests and * aggregates the responses./* ww w .j av a 2 s . co m*/ * * @param items the list of items to get attributes for * @param listener class that will be notified when items are ready * @throws SDBException wraps checked exceptions */ public void getItemsAttributes(List<String> items, ItemListener listener) throws SDBException { ThreadPoolExecutor pool = getThreadPoolExecutor(); pool.setRejectedExecutionHandler(new RejectionHandler()); Counter running = new Counter(0); for (String item : items) { while (pool.getActiveCount() == pool.getMaximumPoolSize()) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } synchronized (running) { running.increment(); } pool.execute(new AttrWorker(getItem(item), running, null, listener)); Thread.yield(); } while (true) { if (running.getValue() == 0) { break; } try { Thread.sleep(500); } catch (InterruptedException ex) { } } if (this.executor == null) { pool.shutdown(); } }
From source file:com.xerox.amazonws.sdb.Domain.java
/** * Gets attributes of given items. This method threads off the get requests and * aggregates the responses.//from w ww .ja v a 2 s . c om * * @param items the list of items to get attributes for * @return the map of items with lists of attributes * @throws SDBException wraps checked exceptions */ public Map<String, List<ItemAttribute>> getItemsAttributes(List<String> items) throws SDBException { Map<String, List<ItemAttribute>> results = new Hashtable<String, List<ItemAttribute>>(); ThreadPoolExecutor pool = getThreadPoolExecutor(); pool.setRejectedExecutionHandler(new RejectionHandler()); Counter running = new Counter(0); for (String item : items) { while (pool.getActiveCount() == pool.getMaximumPoolSize()) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } synchronized (running) { running.increment(); } pool.execute(new AttrWorker(getItem(item), running, results, null)); Thread.yield(); } while (true) { if (running.getValue() == 0) { break; } try { Thread.sleep(500); } catch (InterruptedException ex) { } } if (this.executor == null) { pool.shutdown(); } return results; }
From source file:com.xerox.amazonws.sdb.Domain.java
/** * Gets attributes of items specified in the query string. This method threads off the * get requests and aggregates the responses. * * @param queryString the filter statement * @param listener class that will be notified when items are ready * @throws SDBException wraps checked exceptions *///from ww w.j a v a 2 s.c o m public void listItemsAttributes(String queryString, ItemListener listener) throws SDBException { ThreadPoolExecutor pool = getThreadPoolExecutor(); pool.setRejectedExecutionHandler(new RejectionHandler()); String nextToken = ""; Counter running = new Counter(0); do { try { QueryResult result = listItems(queryString, nextToken, 250); List<Item> items = result.getItemList(); for (Item i : items) { while (pool.getActiveCount() == pool.getMaximumPoolSize()) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } synchronized (running) { running.increment(); } pool.execute(new AttrWorker(i, running, null, listener)); Thread.yield(); } nextToken = result.getNextToken(); } catch (SDBException ex) { System.out.println("Query '" + queryString + "' Failure: "); ex.printStackTrace(); } } while (nextToken != null && nextToken.trim().length() > 0); while (true) { if (running.getValue() == 0) { break; } try { Thread.sleep(500); } catch (InterruptedException ex) { } } if (this.executor == null) { pool.shutdown(); } }
From source file:com.amazonaws.services.simpleworkflow.flow.worker.GenericActivityWorker.java
@Override protected TaskPoller createPoller() { ThreadPoolExecutor tasksExecutor = new ThreadPoolExecutor(1, taskExecutorThreadPoolSize, 1, TimeUnit.MINUTES, new SynchronousQueue<Runnable>()); tasksExecutor.setThreadFactory(/*from ww w .j a va 2 s . c o m*/ new ExecutorThreadFactory(ACTIVITY_THREAD_NAME_PREFIX + " " + getTaskListToPoll() + " ")); tasksExecutor.setRejectedExecutionHandler(new BlockCallerPolicy()); return new ActivityTaskPoller(service, domain, getTaskListToPoll(), activityImplementationFactory, tasksExecutor); }
From source file:com.ngdata.sep.impl.SepConsumer.java
/** * @param subscriptionTimestamp timestamp of when the index subscription became active (or more accurately, not * inactive)/*from w w w. j av a2 s. co m*/ * @param listener listeners that will process the events * @param threadCnt number of worker threads that will handle incoming SEP events * @param hostName hostname to bind to * @param payloadExtractor extracts payloads to include in SepEvents */ public SepConsumer(String subscriptionId, long subscriptionTimestamp, EventListener listener, int threadCnt, String hostName, ZooKeeperItf zk, Configuration hbaseConf, PayloadExtractor payloadExtractor) throws IOException, InterruptedException { Preconditions.checkArgument(threadCnt > 0, "Thread count must be > 0"); this.subscriptionId = SepModelImpl.toInternalSubscriptionName(subscriptionId); this.subscriptionTimestamp = subscriptionTimestamp; this.listener = listener; this.zk = zk; this.hbaseConf = hbaseConf; this.sepMetrics = new SepMetrics(subscriptionId); this.payloadExtractor = payloadExtractor; this.executors = Lists.newArrayListWithCapacity(threadCnt); InetSocketAddress initialIsa = new InetSocketAddress(hostName, 0); if (initialIsa.getAddress() == null) { throw new IllegalArgumentException("Failed resolve of " + initialIsa); } String name = "regionserver/" + initialIsa.toString(); this.rpcServer = new RpcServer(this, name, getServices(), /*HBaseRPCErrorHandler.class, OnlineRegions.class},*/ initialIsa, // BindAddress is IP we got for this server. hbaseConf.getInt("hbase.regionserver.handler.count", 10), hbaseConf.getInt("hbase.regionserver.metahandler.count", 10), hbaseConf, HConstants.QOS_THRESHOLD); this.serverName = new ServerName(hostName, rpcServer.getListenerAddress().getPort(), System.currentTimeMillis()); this.zkWatcher = new ZooKeeperWatcher(hbaseConf, this.serverName.toString(), null); // login the zookeeper client principal (if using security) ZKUtil.loginClient(hbaseConf, "hbase.zookeeper.client.keytab.file", "hbase.zookeeper.client.kerberos.principal", hostName); // login the server principal (if using secure Hadoop) User.login(hbaseConf, "hbase.regionserver.keytab.file", "hbase.regionserver.kerberos.principal", hostName); for (int i = 0; i < threadCnt; i++) { ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); executor.setRejectedExecutionHandler(new WaitPolicy()); executors.add(executor); } }