List of usage examples for java.util.concurrent ThreadFactory newThread
Thread newThread(Runnable r);
From source file:com.ery.estorm.util.Threads.java
/** * Get a named {@link ThreadFactory} that just builds daemon threads. * /* w w w . j av a2s . c o m*/ * @param prefix * name prefix for all threads created from the factory * @param handler * unhandles exception handler to set for all threads * @return a thread factory that creates named, daemon threads with the supplied exception handler and normal priority */ public static ThreadFactory newDaemonThreadFactory(final String prefix, final UncaughtExceptionHandler handler) { final ThreadFactory namedFactory = getNamedThreadFactory(prefix); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = namedFactory.newThread(r); if (handler != null) { t.setUncaughtExceptionHandler(handler); } if (!t.isDaemon()) { t.setDaemon(true); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }; }
From source file:ch.cyberduck.core.http.AbstractHttpWriteFeature.java
public HttpResponseOutputStream<T> write(final Path file, final TransferStatus status, final DelayedHttpEntityCallable<T> command, final DelayedHttpEntity entity) throws BackgroundException { // Signal on enter streaming final CountDownLatch entry = entity.getEntry(); final CountDownLatch exit = new CountDownLatch(1); try {// w w w. j a v a 2s.c o m if (StringUtils.isNotBlank(status.getMime())) { entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, status.getMime())); } else { entity.setContentType(MimeTypeService.DEFAULT_CONTENT_TYPE); } final FutureHttpResponse target = new FutureHttpResponse() { @Override public void run() { try { if (status.isCanceled()) { throw new ConnectionCanceledException(); } response = command.call(entity); } catch (BackgroundException e) { exception = e; } finally { // For zero byte files #writeTo is never called and the entry latch not triggered entry.countDown(); // Continue reading the response exit.countDown(); } } }; final ThreadFactory factory = new NamedThreadFactory(String.format("http-%s", file.getName())); final Thread t = factory.newThread(target); t.start(); // Wait for output stream to become available entry.await(); if (null != target.getException()) { if (target.getException() instanceof BackgroundException) { throw (BackgroundException) target.getException(); } throw new DefaultExceptionMappingService().map(target.getException()); } final OutputStream stream = entity.getStream(); return new HttpResponseOutputStream<T>(stream) { @Override public void flush() throws IOException { stream.flush(); } /** * Only available after this stream is closed. * @return Response from server for upload */ @Override public T getStatus() throws BackgroundException { try { if (status.isCanceled()) { throw new ConnectionCanceledException(); } // Block the calling thread until after the full response from the server // has been consumed. exit.await(); } catch (InterruptedException e) { throw new DefaultExceptionMappingService().map(e); } if (null != target.getException()) { if (target.getException() instanceof BackgroundException) { throw (BackgroundException) target.getException(); } throw new DefaultExceptionMappingService().map(target.getException()); } return target.getResponse(); } }; } catch (InterruptedException e) { log.warn(String.format("Error waiting for output stream for %s", file)); throw new DefaultExceptionMappingService().map(e); } }
From source file:com.wolvereness.overmapped.lib.MultiProcessor.java
public ProperProcessor(int threadCount, final ThreadFactory factory) { final ImmutableList.Builder<Thread> threads = ImmutableList.builder(); while (threadCount-- >= 1) { final Thread thread = factory.newThread(new Runnable() { @Override/*from ww w . ja v a2 s .com*/ public void run() { final BlockingQueue<Task<?>> queue = ProperProcessor.this.queue; try { while (!shutdown) { queue.take().handle(); } } catch (final InterruptedException ex) { if (!shutdown) throw new IllegalStateException("Interrupted innappropriately", ex); } } }); threads.add(thread); } final Iterator<Thread> it = (this.threads = threads.build()).iterator(); final Thread initial = it.next(); if (it.hasNext()) { submit(new Callable<Object>() { @Override public Object call() throws Exception { while (it.hasNext()) { it.next().start(); } return null; } }); } initial.start(); }
From source file:com.navercorp.pinpoint.collector.cluster.zookeeper.ZookeeperLatestJobWorker.java
public ZookeeperLatestJobWorker(ZookeeperClient zookeeperClient, String serverIdentifier) { this.zookeeperClient = zookeeperClient; this.workerState = new WorkerStateContext(); this.collectorUniqPath = bindingPathAndZnode(PINPOINT_COLLECTOR_CLUSTER_PATH, serverIdentifier); final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); this.workerThread = threadFactory.newThread(this); }
From source file:com.navercorp.pinpoint.collector.cluster.zookeeper.ZookeeperJobWorker.java
public void start() { final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true); this.workerThread = threadFactory.newThread(this); switch (this.workerState.getCurrentState()) { case NEW:// w ww. j a va 2 s.c o m if (this.workerState.changeStateInitializing()) { logger.info("start() started."); workerState.changeStateStarted(); this.workerThread.start(); logger.info("start() completed."); break; } case INITIALIZING: logger.info("start() failed. cause: already initializing."); break; case STARTED: logger.info("start() failed. cause: already initializing."); break; case DESTROYING: throw new IllegalStateException("Already destroying."); case STOPPED: throw new IllegalStateException( ClassUtils.simpleClassName(this) + " start() failed. caused:Already stopped."); case ILLEGAL_STATE: throw new IllegalStateException( ClassUtils.simpleClassName(this) + " start() failed. caused:Invalid State."); } }
From source file:com.alibaba.wasp.master.AssignmentManager.java
/** * Get a named {@link java.util.concurrent.ThreadFactory} that just builds daemon threads * * @param prefix//from w ww . j a v a 2 s .c o m * name prefix for all threads created from the factory * @return a thread factory that creates named, daemon threads */ private static ThreadFactory newDaemonThreadFactory(final String prefix) { final ThreadFactory namedFactory = Threads.getNamedThreadFactory(prefix); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = namedFactory.newThread(r); if (!t.isDaemon()) { t.setDaemon(true); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }; }
From source file:com.alibaba.napoli.gecko.service.timer.HashedWheelTimer.java
/** * Creates a new timer.//from www. ja va 2 s . com * * @param threadFactory * a {@link ThreadFactory} that creates a background * {@link Thread} which is dedicated to {@link TimerTask} * execution. * @param tickDuration * the duration between tick * @param unit * the time unit of the {@code tickDuration} * @param ticksPerWheel * @param maxTimerCapacity * the size of the wheel */ public HashedWheelTimer(final ThreadFactory threadFactory, long tickDuration, final TimeUnit unit, final int ticksPerWheel, final int maxTimerCapacity) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel); } if (maxTimerCapacity <= 0) { throw new IllegalArgumentException("maxTimerCapacity must be greater than 0: " + maxTimerCapacity); } // Normalize ticksPerWheel to power of two and initialize the wheel. this.wheel = createWheel(ticksPerWheel); this.iterators = createIterators(this.wheel); this.maxTimerCapacity = maxTimerCapacity; this.mask = this.wheel.length - 1; // Convert tickDuration to milliseconds. this.tickDuration = tickDuration = unit.toMillis(tickDuration); // Prevent overflow. if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / this.wheel.length) { throw new IllegalArgumentException("tickDuration is too long: " + tickDuration + ' ' + unit); } this.roundDuration = tickDuration * this.wheel.length; this.workerThread = threadFactory .newThread(new ThreadRenamingRunnable(this.worker, "Hashed wheel timer #" + id.incrementAndGet())); // Misuse check final int activeInstances = HashedWheelTimer.activeInstances.incrementAndGet(); if (activeInstances >= MISUSE_WARNING_THRESHOLD && loggedMisuseWarning.compareAndSet(false, true)) { logger.debug("There are too many active " + HashedWheelTimer.class.getSimpleName() + " instances (" + activeInstances + ") - you should share the small number " + "of instances to avoid excessive resource consumption."); } }
From source file:edu.uga.cs.fluxbuster.clustering.ClusterGenerator.java
/** * Compute a distance matrix from a list of candidate flux domains with * a maximum number of calculation threads. * * @param cfds the list of candidate flux domains * @param maxnumthreads the thread ceiling * @return the vector of values in the distance matrix in row major * order//from w ww . j a v a 2 s.c o m */ private Vector<Float> computeDistanceMatrixMultiThreaded(List<CandidateFluxDomain> cfds, int maxnumthreads) { Vector<Float> retval = new Vector<Float>(); ThreadFactory tf = Executors.defaultThreadFactory(); double gamma = Double.parseDouble(localprops.getProperty(GAMMAKEY)); ArrayList<Thread> threads = new ArrayList<Thread>(); ArrayList<HashSet<Integer>> threadrows = new ArrayList<HashSet<Integer>>(); int interval = (int) Math.ceil((cfds.size() - 1) / (double) maxnumthreads); int left = 0; int right = cfds.size() - 2; HashSet<Integer> curset = null; boolean addLeftFirst = true; while (left <= right) { if (curset == null) { curset = new HashSet<Integer>(); } if (curset.size() == interval) { threadrows.add(curset); curset = null; } else { if (addLeftFirst) { curset.add(left++); } else { curset.add(right--); } addLeftFirst = !addLeftFirst; if (curset.size() == interval) { continue; } if (addLeftFirst) { curset.add(left++); } else { curset.add(right--); } } } if (curset != null && curset.size() > 0) { threadrows.add(curset); } ArrayList<Vector<Float>> resultsList = new ArrayList<Vector<Float>>(cfds.size()); // this is necessary to make sure that the proper indexes exist in // resultsList before being accessed by the threads for (int i = 0; i < cfds.size() - 1; i++) { resultsList.add(null); } for (int i = 0; i < threadrows.size(); i++) { Thread t = tf.newThread(new DistanceMatrixCalculator(gamma, threadrows.get(i), cfds, resultsList)); threads.add(t); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < resultsList.size(); i++) { retval.addAll(resultsList.get(i)); } return retval; }
From source file:org.apache.hadoop.fs.s3r.S3RFileSystem.java
/** * Get a named {@link ThreadFactory} that just builds daemon threads. * @param prefix name prefix for all threads created from the factory * @return a thread factory that creates named, daemon threads with * the supplied exception handler and normal priority *//*from w w w. jav a 2 s .c o m*/ private static ThreadFactory newDaemonThreadFactory(final String prefix) { final ThreadFactory namedFactory = getNamedThreadFactory(prefix); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = namedFactory.newThread(r); if (!t.isDaemon()) { t.setDaemon(true); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }; }