List of usage examples for java.util.concurrent ThreadFactory ThreadFactory
ThreadFactory
From source file:com.amazon.mws.shared.MwsConnection.java
/** * Get the shared executor service that is used by async calls if no * executor is supplied.//ww w. j a v a 2 s . com * * @return The shared executor service. */ private ExecutorService getSharedES() { synchronized (this.getClass()) { if (sharedES != null) { return sharedES; } sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); public Thread newThread(Runnable task) { Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement()); thread.setDaemon(true); thread.setPriority(Thread.NORM_PRIORITY); return thread; } }, new RejectedExecutionHandler() { public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) { if (!executor.isShutdown()) { log.warn("MWSClient async queue full, running on calling thread."); task.run(); } else { throw new RejectedExecutionException(); } } }); return sharedES; } }
From source file:com.amazonservices.mws.client.MwsConnection.java
/** * Get the shared executor service that is used by async calls if no * executor is supplied.//from w w w . j av a 2 s .c om * * @return The shared executor service. */ private ExecutorService getSharedES() { synchronized (this.getClass()) { if (sharedES != null) { return sharedES; } sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); //@Override public Thread newThread(Runnable task) { Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement()); thread.setDaemon(true); thread.setPriority(Thread.NORM_PRIORITY); return thread; } }, new RejectedExecutionHandler() { //@Override public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) { if (!executor.isShutdown()) { log.warn("MWSClient async queue full, running on calling thread."); task.run(); } else { throw new RejectedExecutionException(); } } }); return sharedES; } }
From source file:it.crs4.pydoop.mapreduce.pipes.TaskLog.java
public static ScheduledExecutorService createLogSyncer() { final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override/*from w w w . ja v a 2s. c om*/ public Thread newThread(Runnable r) { final Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); t.setName("Thread for syncLogs"); return t; } }); ShutdownHookManager.get().addShutdownHook(new Runnable() { @Override public void run() { TaskLog.syncLogsShutdown(scheduler); } }, 50); scheduler.scheduleWithFixedDelay(new Runnable() { @Override public void run() { TaskLog.syncLogs(); } }, 0L, 5L, TimeUnit.SECONDS); return scheduler; }
From source file:mondrian.olap.Util.java
/** * Creates an {@link ScheduledExecutorService} object backed by a * thread pool with a fixed number of threads.. * @param maxNbThreads Maximum number of concurrent * threads.//w w w . ja v a2 s . co m * @param name The name of the threads. * @return An scheduled executor service preconfigured. */ public static ScheduledExecutorService getScheduledExecutorService(final int maxNbThreads, final String name) { return Executors.newScheduledThreadPool(maxNbThreads, new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable r) { final Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setDaemon(true); thread.setName(name + '_' + counter.incrementAndGet()); return thread; } }); }
From source file:org.micromanager.plugins.magellan.imagedisplay.DisplayOverlayer.java
private void createExecutors() { taskExecutor_ = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override// w w w . j av a2s . c o m public Thread newThread(Runnable r) { return new Thread(r, display_.getTitle() + " overalyer task thread"); } }); overlayMakerExecutor_ = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, display_.getTitle() + " overaly maker thread"); } }); }
From source file:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java
protected String getPassword() throws MojoExecutionException { if (password == null) { password = System.getProperty(PROFILE_SYNC_PASSWORD_PROPERTY); //still blank, try the passed in param if (StringUtils.isBlank(password)) { password = profileSyncPassword; }//from w w w. j a v a 2 s. co m //still no password, prompt if allowed if (StringUtils.isBlank(password) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) { Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { try { if (!disableHintGiven) { System.out.println("To disable remote sync during build, add '-D" + PROFILE_SYNC_DISABLE + "=true' to your maven command"); disableHintGiven = true; } System.out.println("Enter the " + config_.getChangeSetUrlType().name() + " password for the Profiles/Changset remote store: (" + config_.getChangeSetUrl() + "):"); //Use console if available, for password masking Console console = System.console(); if (console != null) { password = new String(console.readPassword()); } else { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); password = br.readLine(); } } catch (IOException e) { throw new MojoExecutionException("Error reading password from console"); } return null; } }; try { Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "User Password Prompt Thread"); t.setDaemon(true); return t; } }).submit(callable).get(2, TimeUnit.MINUTES); } catch (TimeoutException | InterruptedException e) { throw new MojoExecutionException("Password not provided within timeout"); } catch (ExecutionException ee) { throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause() : new MojoExecutionException("Unexpected", ee.getCause())); } } } return password; }
From source file:org.apache.lens.driver.es.ESDriver.java
@Override public void configure(Configuration conf, String driverType, String driverName) throws LensException { super.configure(conf, driverType, driverName); config = new ESDriverConfig(getConf()); Class klass;/* w w w .j ava2s . c o m*/ try { klass = Class.forName(getConf().get(ESDriverConfig.CLIENT_CLASS_KEY)); if (klass != null) { log.debug("Picked up class {}", klass); if (ESClient.class.isAssignableFrom(klass)) { final Constructor constructor = klass.getConstructor(ESDriverConfig.class, Configuration.class); esClient = (ESClient) constructor.newInstance(config, getConf()); log.debug("Successfully instantiated es client of type {}", klass); } } else { log.debug("Client class not provided, falling back to the default Jest client"); esClient = new JestClientImpl(config, conf); } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { log.error("ES driver {} cannot start!", getFullyQualifiedName(), e); throw new LensException("Cannot start es driver", e); } log.info("ES Driver {} configured", getFullyQualifiedName()); asyncQueryPool = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread th = new Thread(runnable); th.setName("lens-driver-es-" + THID.incrementAndGet()); return th; } }); }
From source file:org.m2x.rssreader.service.FetcherService.java
private int refreshFeeds() { ContentResolver cr = getContentResolver(); final Cursor cursor = cr.query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID, null, null, null); int nbFeed = cursor.getCount(); ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBER, new ThreadFactory() { @Override/*w w w.jav a 2 s . c om*/ public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } }); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor); while (cursor.moveToNext()) { final String feedId = cursor.getString(0); completionService.submit(new Callable<Integer>() { @Override public Integer call() { int result = 0; try { result = refreshFeed(feedId); } catch (Exception ignored) { } return result; } }); } cursor.close(); int globalResult = 0; for (int i = 0; i < nbFeed; i++) { try { Future<Integer> f = completionService.take(); globalResult += f.get(); } catch (Exception ignored) { } } executor.shutdownNow(); // To purge all threads return globalResult; }
From source file:com.dtolabs.rundeck.core.execution.impl.jsch.JschNodeExecutor.java
public NodeExecutorResult executeCommand(final ExecutionContext context, final String[] command, final INodeEntry node) { if (null == node.getHostname() || null == node.extractHostname()) { return NodeExecutorResultImpl.createFailure(StepFailureReason.ConfigurationFailure, "Hostname must be set to connect to remote node '" + node.getNodename() + "'", node); }/*from ww w . j a v a2s .co m*/ final ExecutionListener listener = context.getExecutionListener(); final Project project = new Project(); AntSupport.addAntBuildListener(listener, project); boolean success = false; final ExtSSHExec sshexec; //perform jsch sssh command final NodeSSHConnectionInfo nodeAuthentication = new NodeSSHConnectionInfo(node, framework, context); final int timeout = nodeAuthentication.getSSHTimeout(); try { sshexec = SSHTaskBuilder.build(node, command, project, context.getDataContext(), nodeAuthentication, context.getLoglevel(), listener); } catch (SSHTaskBuilder.BuilderException e) { return NodeExecutorResultImpl.createFailure(StepFailureReason.ConfigurationFailure, e.getMessage(), node); } //Sudo support final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(null, r, "SudoResponder " + node.getNodename() + ": " + System.currentTimeMillis()); } }); final Future<ResponderTask.ResponderResult> responderFuture; final SudoResponder sudoResponder = SudoResponder.create(node, framework, context); Runnable responderCleanup = null; if (sudoResponder.isSudoEnabled() && sudoResponder.matchesCommandPattern(command[0])) { final DisconnectResultHandler resultHandler = new DisconnectResultHandler(); //configure two piped i/o stream pairs, to connect to the input/output of the SSH connection final PipedInputStream responderInput = new PipedInputStream(); final PipedOutputStream responderOutput = new PipedOutputStream(); final PipedInputStream jschInput = new PipedInputStream(); //lead pipe allows connected inputstream to close and not hang the writer to this stream final PipedOutputStream jschOutput = new LeadPipeOutputStream(); try { responderInput.connect(jschOutput); jschInput.connect(responderOutput); } catch (IOException e) { return NodeExecutorResultImpl.createFailure(StepFailureReason.IOFailure, e.getMessage(), node); } //first sudo prompt responder ResponderTask responder = new ResponderTask(sudoResponder, responderInput, responderOutput, resultHandler); /** * Callable will be executed by the ExecutorService */ final Callable<ResponderTask.ResponderResult> responderResultCallable; //if 2nd responder final SudoResponder sudoResponder2 = SudoResponder.create(node, framework, context, SUDO2_OPT_PREFIX, DEFAULT_SUDO2_PASSWORD_OPTION, DEFAULT_SUDO2_COMMAND_PATTERN); if (sudoResponder2.isSudoEnabled() && sudoResponder2.matchesCommandPattern(CLIUtils.generateArgline(null, command, false))) { logger.debug("Enable second sudo responder"); sudoResponder2.setDescription("Second " + SudoResponder.DEFAULT_DESCRIPTION); sudoResponder.setDescription("First " + SudoResponder.DEFAULT_DESCRIPTION); //sequence of the first then the second sudo responder responderResultCallable = responder.createSequence(sudoResponder2); } else { responderResultCallable = responder; } //set up SSH execution sshexec.setAllocatePty(true); sshexec.setInputStream(jschInput); sshexec.setSecondaryStream(jschOutput); sshexec.setDisconnectHolder(resultHandler); responderFuture = executor.submit(responderResultCallable); //close streams after responder is finished responderCleanup = new Runnable() { public void run() { logger.debug("SudoResponder shutting down..."); try { responderInput.close(); } catch (IOException e) { e.printStackTrace(); } try { responderOutput.flush(); responderOutput.close(); } catch (IOException e) { e.printStackTrace(); } //executor pool shutdown executor.shutdownNow(); } }; executor.submit(responderCleanup); } else { responderFuture = null; } if (null != context.getExecutionListener()) { context.getExecutionListener().log(3, "Starting SSH Connection: " + nodeAuthentication.getUsername() + "@" + node.getHostname() + " (" + node.getNodename() + ")"); } String errormsg = null; FailureReason failureReason = null; try { sshexec.execute(); success = true; } catch (BuildException e) { final ExtractFailure extractJschFailure = extractFailure(e, node, timeout, framework); errormsg = extractJschFailure.getErrormsg(); failureReason = extractJschFailure.getReason(); context.getExecutionListener().log(0, errormsg); } if (null != responderCleanup) { responderCleanup.run(); } shutdownAndAwaitTermination(executor); if (null != responderFuture) { try { logger.debug("Waiting 5 seconds for responder future result"); final ResponderTask.ResponderResult result = responderFuture.get(5, TimeUnit.SECONDS); logger.debug("Responder result: " + result); if (!result.isSuccess() && !result.isInterrupted()) { context.getExecutionListener().log(0, result.getResponder().toString() + " failed: " + result.getFailureReason()); } } catch (InterruptedException e) { //ignore } catch (java.util.concurrent.ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { //ignore } } final int resultCode = sshexec.getExitStatus(); if (success) { return NodeExecutorResultImpl.createSuccess(node); } else { return NodeExecutorResultImpl.createFailure(failureReason, errormsg, node, resultCode); } }