List of usage examples for java.util.concurrent ThreadFactory ThreadFactory
ThreadFactory
From source file:org.wso2.carbon.bpel.core.ode.integration.BPELServerImpl.java
private ThreadFactory createThreadFactory() { return new ThreadFactory() { private int threadNumber = 0; public Thread newThread(Runnable r) { threadNumber += 1;//from w w w. j av a 2s.c o m Thread t = new Thread(r, "BPELServer-" + threadNumber); t.setDaemon(true); return t; } }; }
From source file:SwingWorker.java
/** * returns workersExecutorService./*from ww w . ja v a 2s . c o m*/ * * returns the service stored in the appContext or creates it if * necessary. If the last one it triggers autoShutdown thread to * get started. * * @return ExecutorService for the {@code SwingWorkers} * @see #startAutoShutdownThread */ private static synchronized ExecutorService getWorkersExecutorService() { if (executorService == null) { //this creates non-daemon threads. ThreadFactory threadFactory = new ThreadFactory() { final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); public Thread newThread(final Runnable r) { Thread thread = defaultFactory.newThread(r); thread.setName("SwingWorker-" + thread.getName()); return thread; } }; /* * We want a to have no more than MAX_WORKER_THREADS * running threads. * * We want a worker thread to wait no longer than 1 second * for new tasks before terminating. */ executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory) { private final ReentrantLock pauseLock = new ReentrantLock(); private final Condition unpaused = pauseLock.newCondition(); private boolean isPaused = false; private final ReentrantLock executeLock = new ReentrantLock(); @Override public void execute(Runnable command) { /* * ThreadPoolExecutor first tries to run task * in a corePool. If all threads are busy it * tries to add task to the waiting queue. If it * fails it run task in maximumPool. * * We want corePool to be 0 and * maximumPool to be MAX_WORKER_THREADS * We need to change the order of the execution. * First try corePool then try maximumPool * pool and only then store to the waiting * queue. We can not do that because we would * need access to the private methods. * * Instead we enlarge corePool to * MAX_WORKER_THREADS before the execution and * shrink it back to 0 after. * It does pretty much what we need. * * While we changing the corePoolSize we need * to stop running worker threads from accepting new * tasks. */ //we need atomicity for the execute method. executeLock.lock(); try { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } setCorePoolSize(MAX_WORKER_THREADS); super.execute(command); setCorePoolSize(0); pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } finally { executeLock.unlock(); } } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); pauseLock.lock(); try { while (isPaused) { unpaused.await(); } } catch (InterruptedException ignore) { } finally { pauseLock.unlock(); } } }; } return executorService; }
From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java
private int refreshFeeds(final long keepDateBorderTime) { ContentResolver cr = getContentResolver(); final Cursor cursor = cr.query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID, null, null, null); int nbFeed = (cursor != null) ? cursor.getCount() : 0; ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBER, new ThreadFactory() { @Override/*from www . j a v a 2 s.co m*/ public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } }); CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor); while (cursor != null && cursor.moveToNext()) { final String feedId = cursor.getString(0); completionService.submit(new Callable<Integer>() { @Override public Integer call() { int result = 0; try { result = refreshFeed(feedId, keepDateBorderTime); } catch (Exception e) { Log.e(TAG, "Error refreshing feed " + e.getMessage()); } return result; } }); } if (cursor != null) cursor.close(); int globalResult = 0; for (int i = 0; i < nbFeed; i++) { try { Future<Integer> f = completionService.take(); // ModPrivacyVandaag: the count of new articles after a feed is refreshed globalResult += f.get(); } catch (Exception e) { Log.e(TAG, "Error counting new articles " + e.getMessage()); } } executor.shutdownNow(); // To purge all threads return globalResult; // ModPrivacyVandaag: As far as I can see: this contains the number of new articles from a refresh of the feeds. }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation * that we need for testing./*from w w w.j ava 2 s.c o m*/ */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); context.setConfigurations(new Configuration[] { new WebXmlConfiguration(), new NoListenerConfiguration() }); server.setHandler(context); context.setMimeTypes(MIME_TYPES); SocketConnector connector = new SocketConnector(); connector.setHeaderBufferSize(12 * 1024); // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL if (System.getProperty("port") != null) connector.setPort(Integer.parseInt(System.getProperty("port"))); server.setThreadPool(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Jetty Thread Pool"); return t; } }))); server.addConnector(connector); server.addUserRealm(configureUserRealm()); server.start(); localPort = connector.getLocalPort(); LOGGER.log(Level.INFO, "Running on {0}", getURL()); return context.getServletContext(); }
From source file:org.talend.commons.utils.threading.Locker.java
private void initThreadsPool() { treadsPool = Executors.newCachedThreadPool(new ThreadFactory() { @Override/*from www. ja v a 2 s. c o m*/ public Thread newThread(Runnable r) { Thread newThread = Executors.defaultThreadFactory().newThread(r); newThread.setName(newThread.getName() + "_" + Locker.class.getSimpleName()); //$NON-NLS-1$ return newThread; } }); }
From source file:org.apache.helix.messaging.handling.HelixTaskExecutor.java
void init() { LOG.info("Init HelixTaskExecutor"); if (_messageQueueMonitor != null) { _messageQueueMonitor.init();// www. jav a 2 s . co m } _isShuttingDown = false; // Re-init all existing factories for (final String msgType : _hdlrFtyRegistry.keySet()) { MsgHandlerFactoryRegistryItem item = _hdlrFtyRegistry.get(msgType); ExecutorService newPool = Executors.newFixedThreadPool(item.threadPoolSize(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "HelixTaskExecutor-message_handle_" + msgType); } }); ExecutorService prevPool = _executorMap.putIfAbsent(msgType, newPool); if (prevPool != null) { // Will happen if we register and call init LOG.info("Skip init a new thread pool for type: " + msgType + ", already existing pool: " + prevPool + ", isShutdown: " + prevPool.isShutdown()); newPool.shutdown(); } else { _monitor.createExecutorMonitor(msgType, newPool); } } }
From source file:voldemort.utils.RebalanceUtils.java
public static ExecutorService createExecutors(int numThreads) { return Executors.newFixedThreadPool(numThreads, new ThreadFactory() { @Override// ww w . ja v a 2s.c o m public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setName(r.getClass().getName()); return thread; } }); }
From source file:com.hubcap.task.TaskRunner.java
/** * Processes the 'START' state/*ww w.ja v a2s . c o m*/ */ protected void processStateStart() { if (this.taskState == TaskRunnerState.START) { if (helperPool == null) { // get a stable thread count up to MAX_HELPER_THREADS based on // CPU LOAD per helper int maxHelpers = ThreadUtils.getStableThreadCount(CPU_LOAD_TRH, CPU_WAIT_TRH, CPU_COMPUTE_TRH, Constants.MAX_HELPER_THREADS); if (this.helperFactory == null) { this.helperFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { if (helpers.contains(r)) { throw new IllegalStateException("Cannot add duplicate runnable to running tasks"); } Thread thread = new Thread(r); thread.setDaemon(false); thread.setName("TaskRunnerHelper-" + helperCount.getAndIncrement()); taskThreads.add(thread); return thread; } }; } // create the pool but don't fire up any helpers helperPool = Executors.newFixedThreadPool(maxHelpers, TaskRunner.taskRunnerThreadFactory); } TaskRunnerListener[] list = listeners.toArray(new TaskRunnerListener[listeners.size()]); for (int i = 0; i < list.length; i++) { TaskRunnerListener listener = list[i]; listener.onTaskStart(this); } try { // create the task model using the input arguments setTaskState(TaskRunnerState.ACTIVE); this.taskModel = CLIOptionBuilder.buildInputOptionsModel(this.taskArgs); synchronized (sharedResource_resultModel) { sharedResource_resultModel.addTaskModel(taskModel); } } catch (ParseException e) { ErrorUtils.printStackTrace(e); setTaskState(TaskRunnerState.ERROR); this.canRecoverFromError = true; this.errorMessage = "Inputs were malformed, please try again"; } } else { System.err.println("Can't Start...Task State is: " + this.taskState); } }