List of usage examples for java.util.concurrent ThreadFactory ThreadFactory
ThreadFactory
From source file:org.apache.helix.messaging.handling.HelixTaskExecutor.java
@Override public void registerMessageHandlerFactory(String type, MessageHandlerFactory factory, int threadpoolSize) { if (!factory.getMessageTypes().contains(type)) { throw new HelixException( "Message factory type mismatch. Type: " + type + ", factory: " + factory.getMessageTypes()); }//from www . ja v a 2 s.co m _isShuttingDown = false; MsgHandlerFactoryRegistryItem newItem = new MsgHandlerFactoryRegistryItem(factory, threadpoolSize); MsgHandlerFactoryRegistryItem prevItem = _hdlrFtyRegistry.putIfAbsent(type, newItem); if (prevItem == null) { ExecutorService newPool = Executors.newFixedThreadPool(threadpoolSize, new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "HelixTaskExecutor-message_handle_thread"); } }); ExecutorService prevExecutor = _executorMap.putIfAbsent(type, newPool); if (prevExecutor != null) { LOG.warn("Skip creating a new thread pool for type: " + type + ", already existing pool: " + prevExecutor + ", isShutdown: " + prevExecutor.isShutdown()); newPool.shutdown(); newPool = null; } else { _monitor.createExecutorMonitor(type, newPool); } LOG.info("Registered message handler factory for type: " + type + ", poolSize: " + threadpoolSize + ", factory: " + factory + ", pool: " + _executorMap.get(type)); } else { LOG.info("Skip register message handler factory for type: " + type + ", poolSize: " + threadpoolSize + ", factory: " + factory + ", already existing factory: " + prevItem.factory()); newItem = null; } }
From source file:org.mobicents.servlet.restcomm.sms.smpp.SmppService.java
private void initializeSmppConnections() { Configuration smppConfiguration = this.configuration.subset("smpp"); List<Object> smppConnections = smppConfiguration.getList("connections.connection.name"); int smppConnecsSize = smppConnections.size(); if (smppConnecsSize == 0) { logger.warning("No SMPP Connections defined!"); return;/*from w w w.j av a2 s .c o m*/ } for (int count = 0; count < smppConnecsSize; count++) { String name = smppConfiguration.getString("connections.connection(" + count + ").name"); String systemId = smppConfiguration.getString("connections.connection(" + count + ").systemid"); String peerIp = smppConfiguration.getString("connections.connection(" + count + ").peerip"); int peerPort = smppConfiguration.getInt("connections.connection(" + count + ").peerport"); SmppBindType bindtype = SmppBindType .valueOf(smppConfiguration.getString("connections.connection(" + count + ").bindtype")); if (bindtype == null) { logger.warning("Bindtype for SMPP name=" + name + " is not specified. Using default TRANSCEIVER"); } String password = smppConfiguration.getString("connections.connection(" + count + ").password"); String systemType = smppConfiguration.getString("connections.connection(" + count + ").systemtype"); byte interfaceVersion = smppConfiguration .getByte("connections.connection(" + count + ").interfaceversion"); byte ton = smppConfiguration.getByte("connections.connection(" + count + ").ton"); byte npi = smppConfiguration.getByte("connections.connection(" + count + ").npi"); String range = smppConfiguration.getString("connections.connection(" + count + ").range"); Address address = null; if (ton != -1 && npi != -1 && range != null) { address = new Address(ton, npi, range); } int windowSize = smppConfiguration.getInt("connections.connection(" + count + ").windowsize"); long windowWaitTimeout = smppConfiguration .getLong("connections.connection(" + count + ").windowwaittimeout"); long connectTimeout = smppConfiguration.getLong("connections.connection(" + count + ").connecttimeout"); long requestExpiryTimeout = smppConfiguration .getLong("connections.connection(" + count + ").requestexpirytimeout"); long windowMonitorInterval = smppConfiguration .getLong("connections.connection(" + count + ").windowmonitorinterval"); boolean logBytes = smppConfiguration.getBoolean("connections.connection(" + count + ").logbytes"); boolean countersEnabled = smppConfiguration .getBoolean("connections.connection(" + count + ").countersenabled"); long enquireLinkDelay = smppConfiguration .getLong("connections.connection(" + count + ").enquirelinkdelay"); Smpp smpp = new Smpp(name, systemId, peerIp, peerPort, bindtype, password, systemType, interfaceVersion, address, connectTimeout, windowSize, windowWaitTimeout, requestExpiryTimeout, windowMonitorInterval, countersEnabled, logBytes, enquireLinkDelay); this.smppList.add(smpp); if (logger.isInfoEnabled()) { logger.info("creating new SMPP connection " + smpp); } } // for monitoring thread use, it's preferable to create your own // instance of an executor and cast it to a ThreadPoolExecutor from // Executors.newCachedThreadPool() this permits exposing thinks like // executor.getActiveCount() via JMX possible no point renaming the // threads in a factory since underlying Netty framework does not easily // allow you to customize your thread names this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); // to enable automatic expiration of requests, a second scheduled // executor is required which is what a monitor task will be executed // with - this is probably a thread pool that can be shared with between // all client bootstraps this.monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, new ThreadFactory() { private AtomicInteger sequence = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("SmppServer-SessionWindowMonitorPool-" + sequence.getAndIncrement()); return t; } }); // a single instance of a client bootstrap can technically be shared // between any sessions that are created (a session can go to any // different number of SMSCs) - each session created under a client // bootstrap will use the executor and monitorExecutor set in its // constructor - just be *very* careful with the "expectedSessions" // value to make sure it matches the actual number of total concurrent // open sessions you plan on handling - the underlying netty library // used for NIO sockets essentially uses this value as the max number of // threads it will ever use, despite the "max pool size", etc. set on // the executor passed in here // Setting expected session to be 25. May be this should be // configurable? this.clientBootstrap = new DefaultSmppClient(this.executor, 25, monitorExecutor); this.smppClientOpsThread = new SmppClientOpsThread(this.clientBootstrap, outboundInterface("udp").getPort(), smppMessageHandler); (new Thread(this.smppClientOpsThread)).start(); for (Smpp smpp : this.smppList) { this.smppClientOpsThread.scheduleConnect(smpp); } if (logger.isInfoEnabled()) { logger.info("SMPP Service started"); } }
From source file:org.apache.nifi.processors.standard.ExecuteProcess.java
@OnScheduled public void setupExecutor(final ProcessContext context) { executor = Executors.newFixedThreadPool(context.getMaxConcurrentTasks() * 2, new ThreadFactory() { private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); @Override// w ww . j av a 2s . c om public Thread newThread(final Runnable r) { final Thread t = defaultFactory.newThread(r); t.setName("ExecuteProcess " + getIdentifier() + " Task"); return t; } }); }
From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java
public RunMiNiFi(final File bootstrapConfigFile) throws IOException { this.bootstrapConfigFile = bootstrapConfigFile; loggingExecutor = Executors.newFixedThreadPool(2, new ThreadFactory() { @Override/*from w ww . j a v a2 s . co m*/ public Thread newThread(final Runnable runnable) { final Thread t = Executors.defaultThreadFactory().newThread(runnable); t.setDaemon(true); t.setName("MiNiFi logging handler"); return t; } }); }
From source file:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java
protected String getUsername() throws MojoExecutionException { if (username == null) { username = System.getProperty(PROFILE_SYNC_USERNAME_PROPERTY); //still blank, try property if (StringUtils.isBlank(username)) { username = profileSyncUsername; }//from www .j av a 2 s. c o m //still no username, prompt if allowed if (StringUtils.isBlank(username) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) { Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { if (!disableHintGiven) { System.out.println("To disable remote sync during build, add '-D" + PROFILE_SYNC_DISABLE + "=true' to your maven command"); disableHintGiven = true; } try { System.out.println("Enter the " + config_.getChangeSetUrlType().name() + " username for the Profiles/Changset remote store (" + config_.getChangeSetUrl() + "):"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); username = br.readLine(); } catch (IOException e) { throw new MojoExecutionException("Error reading username from console"); } return null; } }; try { Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "User Prompt Thread"); t.setDaemon(true); return t; } }).submit(callable).get(2, TimeUnit.MINUTES); } catch (TimeoutException | InterruptedException e) { throw new MojoExecutionException("Username not provided within timeout"); } catch (ExecutionException ee) { throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause() : new MojoExecutionException("Unexpected", ee.getCause())); } } } return username; }
From source file:org.apache.hadoop.hbase.util.ModifyRegionUtils.java
static ThreadPoolExecutor getRegionOpenAndInitThreadPool(final Configuration conf, final String threadNamePrefix, int regionNumber) { int maxThreads = Math.min(regionNumber, conf.getInt("hbase.hregion.open.and.init.threads.max", 10)); ThreadPoolExecutor regionOpenAndInitThreadPool = Threads.getBoundedCachedThreadPool(maxThreads, 30L, TimeUnit.SECONDS, new ThreadFactory() { private int count = 1; @Override//www.j a va 2 s .co m public Thread newThread(Runnable r) { Thread t = new Thread(r, threadNamePrefix + "-" + count++); return t; } }); return regionOpenAndInitThreadPool; }
From source file:org.jumpmind.symmetric.service.impl.DataLoaderService.java
public void start() { dataLoadWorkers = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix = parameterService.getEngineName().toLowerCase() + "-data-load-worker-"; public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName(namePrefix + threadNumber.getAndIncrement()); t.setDaemon(false);//from w w w .ja va2 s .com if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }); }
From source file:com.ibm.jaggr.service.impl.deps.DepTree.java
/** * Object constructor. Attempts to de-serialize the cached dependency lists * from disk and then validates the dependency lists based on last-modified * dates, looking for any new or removed files. If the cached dependency * list data cannot be de-serialized, new lists are constructed. Once the * dependency lists have been validated, the list data is serialized back * out to disk./* ww w. j a v a 2s . co m*/ * * @param paths * Collection of URIs which specify the target resources * to be scanned for javascript files. * @param aggregator * The servlet instance for this object * @param stamp * timestamp associated with external override/customization * resources that are check on every server restart * @param clean * If true, then the dependency lists are generated from scratch * rather than by de-serializing and then validating the cached * dependency lists. * @param validateDeps * If true, then validate existing cached dependencies using * file last-modified times. * @throws IOException */ public DepTree(Collection<URI> paths, IAggregator aggregator, long stamp, boolean clean, boolean validateDeps) throws IOException { this.stamp = stamp; IConfig config = aggregator.getConfig(); rawConfig = config.toString(); File cacheDir = new File(aggregator.getWorkingDirectory(), DEPCACHE_DIRNAME); File cacheFile = new File(cacheDir, CACHE_FILE); /* * The de-serialized dependency map. If we have a cached dependency map, * then it will be validated against the last-modified dates of the * current files and only the files that have changed will need to be * re-parsed to update the dependency lists. */ DepTree cached = null; if (!clean) { // If we're not starting clean, try to de-serialize the map from // cache try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(cacheFile)); try { cached = (DepTree) is.readObject(); } finally { try { is.close(); } catch (Exception ignore) { } } } catch (FileNotFoundException e) { /* * Not an error. Just means that the cache file hasn't been * written yet or else it's been deleted. */ if (log.isLoggable(Level.INFO)) log.log(Level.INFO, Messages.DepTree_1); } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); } } // If the cacheBust config param has changed, then do a clean build // of the dependencies. if (cached != null) { if (stamp == 0) { // no init stamp provided. Preserve the cached one. stamp = cached.stamp; } if (stamp > cached.stamp) { // init stamp has been updated. Validate dependencies. validateDeps = true; } cacheBust = aggregator.getOptions().getCacheBust(); if (!StringUtils.equals(cacheBust, cached.cacheBust)) { if (log.isLoggable(Level.INFO)) { log.info(Messages.DepTree_2); } cached = null; } } /* * If we de-serialized a previously saved dependency map, then go with * that. */ if (cached != null && rawConfig.equals(cached.rawConfig) && !validateDeps && !clean) { depMap = cached.depMap; return; } // Initialize the dependency map depMap = new ConcurrentHashMap<URI, DepTreeNode>(); // This can take a while, so print something to the console String msg = MessageFormat.format(Messages.DepTree_3, new Object[] { aggregator.getName() }); ConsoleService cs = new ConsoleService(); cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } // Make sure that all the paths are unique and orthogonal paths = DepUtils.removeRedundantPaths(paths); /* * Create the thread pools, one for the tree builders and one for the * parsers. Since a tree builder thread will wait for all the outstanding * parser threads started by that builder to complete, we need to use two * independent thread pools to guard against the possibility of deadlock * caused by all the threads in the pool being consumed by tree builders * and leaving none available to service the parsers. */ final ThreadGroup treeBuilderTG = new ThreadGroup(TREEBUILDER_TGNAME), parserTG = new ThreadGroup(JSPARSER_TGNAME); ExecutorService treeBuilderExc = Executors.newFixedThreadPool(10, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(treeBuilderTG, r, MessageFormat.format(THREADNAME, new Object[] { treeBuilderTG.getName(), treeBuilderTG.activeCount() })); } }), parserExc = Executors.newFixedThreadPool(20, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(parserTG, r, MessageFormat.format(THREADNAME, new Object[] { parserTG.getName(), parserTG.activeCount() })); } }); // Counter to keep track of number of tree builder threads started AtomicInteger treeBuilderCount = new AtomicInteger(0); // The completion services for the thread pools final CompletionService<URI> parserCs = new ExecutorCompletionService<URI>(parserExc); CompletionService<DepTreeBuilder.Result> treeBuilderCs = new ExecutorCompletionService<DepTreeBuilder.Result>( treeBuilderExc); // Start the tree builder threads to process the paths for (final URI path : paths) { /* * Create or get from cache the root node for this path and * add it to the new map. */ DepTreeNode root = new DepTreeNode(PathUtil.getModuleName(path)); DepTreeNode cachedNode = null; if (cached != null) { cachedNode = cached.depMap.get(path); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_4, new Object[] { path })); } } else { if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_5, new Object[] { path })); } } depMap.put(path, root); treeBuilderCount.incrementAndGet(); treeBuilderCs.submit(new DepTreeBuilder(aggregator, parserCs, path, root, cachedNode)); } // List of parser exceptions LinkedList<Exception> parserExceptions = new LinkedList<Exception>(); /* * Pull the completed tree builder tasks from the completion queue until * all the paths have been processed */ while (treeBuilderCount.decrementAndGet() >= 0) { try { DepTreeBuilder.Result result = treeBuilderCs.take().get(); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_6, new Object[] { result.parseCount, result.dirName })); } } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); parserExceptions.add(e); } } // shutdown the thread pools now that we're done with them parserExc.shutdown(); treeBuilderExc.shutdown(); // If parser exceptions occurred, then rethrow the first one if (parserExceptions.size() > 0) { throw new RuntimeException(parserExceptions.get(0)); } // Prune dead nodes (nodes with no children or dependency lists) for (Map.Entry<URI, DepTreeNode> entry : depMap.entrySet()) { entry.getValue().prune(); } /* * Make sure the cache directory exists before we try to serialize the * dependency map. */ if (!cacheDir.exists()) if (!cacheDir.mkdirs()) { throw new IOException( MessageFormat.format(Messages.DepTree_0, new Object[] { cacheDir.getAbsolutePath() })); } // Serialize the map to the cache directory ObjectOutputStream os; os = new ObjectOutputStream(new FileOutputStream(cacheFile)); try { os.writeObject(this); } finally { try { os.close(); } catch (Exception ignore) { } } msg = MessageFormat.format(Messages.DepTree_7, new Object[] { aggregator.getName() }); // Output that we're done. cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } }
From source file:org.nuxeo.connect.tools.report.client.ReportConnector.java
<A> void connect(Consumer consumer) throws IOException, InterruptedException, ExecutionException { ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { @Override//from w w w . java 2 s . c om public Thread newThread(Runnable target) { Thread thread = new Thread(target, "connect-report"); thread.setDaemon(true); return thread; } }); try { for (ReportServer server : new Discovery()) { try (ServerSocket callback = new ServerSocket(0)) { final Future<?> consumed = executor.submit(new Runnable() { @Override public void run() { String name = Thread.currentThread().getName(); Thread.currentThread().setName("connect-report-consumer-" + server); try (InputStream source = callback.accept().getInputStream()) { consumer.consume(Json.createParser(source)); } catch (IOException | JsonParsingException cause) { throw new AssertionError("Cannot consume connect report", cause); } finally { Thread.currentThread().setName(name); } LogFactory.getLog(ReportConnector.class).info("Consumed " + server); } }); final Future<?> served = executor.submit(new Runnable() { @Override public void run() { String name = Thread.currentThread().getName(); Thread.currentThread().setName("connect-report-server-" + server); InetSocketAddress address = (InetSocketAddress) callback.getLocalSocketAddress(); try { server.run(address.getHostName(), address.getPort()); } catch (IOException cause) { throw new AssertionError("Cannot run connect report", cause); } finally { Thread.currentThread().setName(name); } } }); ExecutionException consumerError = null; try { consumed.get(); } catch (ExecutionException cause) { consumerError = cause; } try { served.get(); } catch (ExecutionException cause) { if (consumerError != null) { consumerError.addSuppressed(cause); throw consumerError; } throw cause; } } } } finally { executor.shutdownNow(); } }
From source file:org.openecomp.sdc.be.dao.titan.TitanGraphClient.java
/** * This method will be invoked ONLY on init time in case Titan storage is * down./*from w w w . j a va2 s .c om*/ */ private void startReconnectTask() { this.reconnectTask = new ReconnectTask(); // Initialize a single threaded scheduler this.reconnectScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "Titan-Reconnect-Task"); } }); logger.info("Scheduling reconnect task {} with interval of {} seconds", reconnectTask, reconnectInterval); reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval, TimeUnit.SECONDS); }