@Override public Thread newThread(Runnable r) { Thread t = defaultFactory.newThread(r); t.setUncaughtExceptionHandler(handler); t.setDaemon(true); // daemonize the thread return t; }
@Test() public void daemonThread() { final ThreadFactory threadFactory = namedThreadFactory( this.getClass().getName(), ThreadFactories.Type.DAEMON, Thread.NORM_PRIORITY); assertTrue(threadFactory.newThread(new MockRunnable()).isDaemon()); }
@Test() public void userThread() { final ThreadFactory threadFactory = namedThreadFactory( this.getClass().getName(), ThreadFactories.Type.USER, Thread.NORM_PRIORITY); assertFalse(threadFactory.newThread(new MockRunnable()).isDaemon()); }
public void shutdown() { LOG.info( format( "shutting down the (LinkedBlockingQueue)ThreadBoundExecutor[%s]", threadFactory.toString())); if (shuttingDown.compareAndSet(false, true)) { final CountDownLatch shuttingDownLatch = new CountDownLatch(queues.size()); for (BlockingQueue<ThreadBoundEvent> queue : queues) { queue.add(new ShutdownTask(shuttingDownLatch)); } try { if (!shuttingDownLatch.await(30, TimeUnit.SECONDS)) { LOG.error( format( "timeout while waiting for (LinkedBlockingQueue)ThreadBoundExecutor[%s] queues to empty", threadFactory.toString())); } } catch (InterruptedException ignore) { // we are shutting down anyway LOG.warn( format( "(LinkedBlockingQueue)ThreadBoundExecutor[%s] shutdown interrupted.", threadFactory.toString())); } } LOG.info( format( "(LinkedBlockingQueue)ThreadBoundExecutor[%s] shut down completed", threadFactory.toString())); }
@Test() public void threadFactory() { final ThreadFactory threadFactory = namedThreadFactory( this.getClass().getName(), ThreadFactories.Type.USER, Thread.NORM_PRIORITY); assertNotNull(threadFactory.newThread(new MockRunnable())); }
@Test() public void maxPriority() { final ThreadFactory threadFactory = namedThreadFactory( this.getClass().getName(), ThreadFactories.Type.USER, Thread.MAX_PRIORITY); assertEquals(Thread.MAX_PRIORITY, threadFactory.newThread(new MockRunnable()).getPriority()); }
@Test() public void threadName() { final ThreadFactory threadFactory = namedThreadFactory( this.getClass().getName(), ThreadFactories.Type.USER, Thread.NORM_PRIORITY); assertEquals( this.getClass().getName() + ":thread-1", threadFactory.newThread(new MockRunnable()).getName()); assertEquals( this.getClass().getName() + ":thread-2", threadFactory.newThread(new MockRunnable()).getName()); }
/** * Construct a new QueuePool instance based on the given {@link Config}. * * @param config The pool configuration to use. */ public QueuePool(Config<T> config) { live = new LinkedTransferQueue<>(); dead = new LinkedTransferQueue<>(); synchronized (config) { config.validate(); ThreadFactory factory = config.getThreadFactory(); metricsRecorder = config.getMetricsRecorder(); expiration = config.getExpiration(); allocator = new QAllocThread<>(live, dead, config, poisonPill); allocatorThread = factory.newThread(allocator); } allocatorThread.start(); }
public ThreadBoundExecutorImpl( ThreadBoundEventProcessor eventProcessor, int maxBatchSize, ThreadFactory threadFactory, int numberOfThreads) { this.threadFactory = threadFactory; LOG.info( format( "Initializing (LinkedBlockingQueue)ThreadBoundExecutor[%s]", threadFactory.toString())); for (int i = 0; i < numberOfThreads; i++) { BlockingQueue<ThreadBoundEvent> queue = new LinkedBlockingQueue<>(); Thread t = threadFactory.newThread(new Consumer(queue, eventProcessor, maxBatchSize)); queues.add(queue); t.start(); } }
/** * Creates a new timer. * * @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 the size of the wheel * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code * null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is * <= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) { 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); } // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); mask = wheel.length - 1; // Convert tickDuration to milliseconds. this.tickDuration = tickDuration = unit.toMillis(tickDuration); // Prevent overflow. if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException("tickDuration is too long: " + tickDuration + ' ' + unit); } roundDuration = tickDuration * wheel.length; workerThread = threadFactory.newThread(worker); }
private LauncherServer() throws IOException { this.refCount = new AtomicLong(0); ServerSocket server = new ServerSocket(); try { server.setReuseAddress(true); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); this.clients = new ArrayList<>(); this.threadIds = new AtomicLong(); this.factory = new NamedThreadFactory(THREAD_NAME_FMT); this.pending = new ConcurrentHashMap<>(); this.timeoutTimer = new Timer("LauncherServer-TimeoutTimer", true); this.server = server; this.running = true; this.serverThread = factory.newThread( new Runnable() { @Override public void run() { acceptConnections(); } }); serverThread.start(); } catch (IOException ioe) { close(); throw ioe; } catch (Exception e) { close(); throw new IOException(e); } }
/** * Creates a new timer. * * @param threadFactory a {@link java.util.concurrent.ThreadFactory} that creates a background * {@link Thread} which is dedicated to {@link TimerTask} execution. * @param duration the duration between ticks * @param ticksPerWheel the size of the wheel */ public HashedWheelTimer( LoggingAdapter logger, ThreadFactory threadFactory, Duration duration, int ticksPerWheel) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (duration == null) { throw new NullPointerException("duration"); } if (duration.toNanos() <= 0) { throw new IllegalArgumentException( "duration must be greater than 0 ns: " + duration.toNanos()); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel); } this.logger = logger; // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); iterators = createIterators(wheel); mask = wheel.length - 1; // Convert to standardized tickDuration this.tickDuration = duration.toNanos(); // Prevent overflow. if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException( "tickDuration is too long: " + tickDuration + ' ' + duration.unit()); } workerThread = threadFactory.newThread(worker); }
/** Return a thread. */ @Override public Thread newThread(Runnable r) { if (shutdown) return null; Runnable wrapper = new Runnable() { /** Keep track of non-daemon threads so shutdown can wait for their termination. */ @Override public void run() { threads.fromNewToRunning(Thread.currentThread()); r.run(); /* If the task has thrown an exception, the code below is * not getting executed. The uncaughtException this.handler * removes the thread from the tracker list and notifies * the completer. */ threads.removeRunning(Thread.currentThread()); if (!hasActiveNonDaemonThreads()) completer.accept(ThreadFactoryTracker.this, null); } }; Thread t = factory.newThread(wrapper); t.setName(t.getName() + "-" + threadName); t.setUncaughtExceptionHandler(handler); threads.addNew(t); return t; }
public Thread newThread(Runnable r) { Thread result = delegate.newThread(r); String s = result.getName(); result.setName(name + "[" + s + "]"); result.setDaemon(daemon); return result; }
private static void initOperationThreads( OperationThread[] operationThreads, ThreadFactory threadFactory) { for (int threadId = 0; threadId < operationThreads.length; threadId++) { OperationThread operationThread = (OperationThread) threadFactory.newThread(null); operationThreads[threadId] = operationThread; operationThread.start(); } }
/** * Construct a new instance. * * @param queueLength the queue length * @param threadFactory the thread factory to use to construct the handler thread */ public AsyncHandler(final int queueLength, final ThreadFactory threadFactory) { recordQueue = new ArrayBlockingQueue<ExtLogRecord>(queueLength); thread = threadFactory.newThread(new AsyncTask()); if (thread == null) { throw new IllegalArgumentException("Thread factory did not create a thread"); } thread.setDaemon(true); }
protected void startRunner() { running = true; runner = timer_thread_factory != null ? timer_thread_factory.newThread(this, "Timer runner") : new Thread(this, "Timer runner"); runner.start(); }
@Before public void setup() { when(factory.newThread(any())) .then( (InvocationOnMock invocation) -> { Runnable r = (Runnable) invocation.getArguments()[0]; createdThread = new Thread(r); return createdThread; }); }
private synchronized boolean createNewThreadIfPossible(Runnable command) { if (numberOfActiveThreads == maxThreads) { return false; } numberOfActiveThreads++; newThreadCreateCount++; Thread newThread = threadFactory.newThread(new WorkerTask(command)); newThread.start(); if (newThreadCreateCount % 5 == 0) { newThreadCreateCount = 0; if (numberOfActiveThreads > (maxThreads - 10)) { logger.info(getName() + " thread count : " + numberOfActiveThreads); } } return true; }
private void acceptConnections() { try { while (running) { final Socket client = server.accept(); TimerTask timeout = new TimerTask() { @Override public void run() { LOG.warning("Timed out waiting for hello message from client."); try { client.close(); } catch (IOException ioe) { // no-op. } } }; ServerConnection clientConnection = new ServerConnection(client, timeout); Thread clientThread = factory.newThread(clientConnection); synchronized (timeout) { clientThread.start(); synchronized (clients) { clients.add(clientConnection); } long timeoutMs = getConnectionTimeout(); // 0 is used for testing to avoid issues with clock resolution / thread scheduling, // and force an immediate timeout. if (timeoutMs > 0) { timeoutTimer.schedule(timeout, getConnectionTimeout()); } else { timeout.run(); } } } } catch (IOException ioe) { if (running) { LOG.log(Level.SEVERE, "Error in accept loop.", ioe); } } }
/** * Will start the consumer if it is not already started. This is designed so you can efficiently * call into this multiple times, and it will safely guarantee that this will only be started * once. * * @param threadFactory ThreadFactory to create new thread from * @param threadName Name to set the new thread to */ public void maybeStart(ThreadFactory threadFactory, String threadName) { /* this looks like a double check but * due to being volatile and only changing * one direction should be safe, as well as the fact * that started is a primitive (can't be half constructed) */ if (started) { return; } synchronized (this) { if (started) { return; } started = true; runningThread = threadFactory.newThread(new ConsumerRunnable()); runningThread.setDaemon(true); if (threadName != null && threadName.length() > 0) { runningThread.setName(threadName); } runningThread.start(); } }
public Thread newThread(Runnable r) { Thread t = threadFactory.newThread(r); t.setDaemon(true); return t; }
public Thread newThread(Runnable r) { Thread thread = defaultFactory.newThread(r); thread.setName(MetricsThreadName); thread.setDaemon(true); return thread; }
public Thread newThread(Runnable runnable) { Thread thread = defaultThreadFactory.newThread(runnable); thread.setName("ServerPluginRegistry-" + thread.getName()); return thread; }
public Thread newThread(Runnable r) { numCreated.incrementAndGet(); return factory.newThread(r); }
private void monitorSocket(final Socket socket) { logger.debug("Launching Monitoring Thread for socket {}", socket); UILogger.getInstance().add("Launching Monitoring Thread for socket " + socket.toString()); Thread t = threadFactory.newThread( new Runnable() { static final int EXPECTED_SIZE = 6; @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { logger.debug("Started monitoring thread"); UILogger.getInstance().add("Started monitoring thread"); try { InputStream in; try { in = socket.getInputStream(); } catch (IOException ioe) { in = null; } byte[] bytes = new byte[EXPECTED_SIZE]; while (in != null && readPacket(in, bytes)) { logger.debug("Error-response packet {}", Utilities.encodeHex(bytes)); UILogger.getInstance() .add("Error-response packet " + Utilities.encodeHex(bytes)); // Quickly close socket, so we won't ever try to send push notifications // using the defective socket. Utilities.close(socket); int command = bytes[0] & 0xFF; if (command != 8) { throw new IOException("Unexpected command byte " + command); } int statusCode = bytes[1] & 0xFF; DeliveryError e = DeliveryError.ofCode(statusCode); int id = Utilities.parseBytes(bytes[2], bytes[3], bytes[4], bytes[5]); logger.debug("Closed connection cause={}; id={}", e, id); UILogger.getInstance().add("Closed connection cause " + e.toString()); UILogger.getInstance().add("Closed connection id " + id); delegate.connectionClosed(e, id); Queue<ApnsNotification> tempCache = new LinkedList<ApnsNotification>(); ApnsNotification notification = null; boolean foundNotification = false; while (!cachedNotifications.isEmpty()) { notification = cachedNotifications.poll(); logger.debug( "Candidate for removal, message id {}", notification.getIdentifier()); UILogger.getInstance() .add("Candidate for removal, message id " + notification.getIdentifier()); if (notification.getIdentifier() == id) { logger.debug("Bad message found {}", notification.getIdentifier()); UILogger.getInstance() .add("Bad message found " + notification.getIdentifier()); foundNotification = true; break; } tempCache.add(notification); } if (foundNotification) { logger.debug( "delegate.messageSendFailed, message id {}", notification.getIdentifier()); UILogger.getInstance() .add( "delegate.messageSendFailed, message id " + notification.getIdentifier()); delegate.messageSendFailed(notification, new ApnsDeliveryErrorException(e)); } else { cachedNotifications.addAll(tempCache); int resendSize = tempCache.size(); logger.warn("Received error for message that wasn't in the cache..."); UILogger.getInstance() .add("Received error for message that wasn't in the cache..."); if (autoAdjustCacheLength) { cacheLength = cacheLength + (resendSize / 2); delegate.cacheLengthExceeded(cacheLength); } logger.debug("delegate.messageSendFailed, unknown id"); UILogger.getInstance().add("delegate.messageSendFailed, unknown id"); delegate.messageSendFailed(null, new ApnsDeliveryErrorException(e)); } int resendSize = 0; while (!cachedNotifications.isEmpty()) { resendSize++; final ApnsNotification resendNotification = cachedNotifications.poll(); logger.debug("Queuing for resend {}", resendNotification.getIdentifier()); UILogger.getInstance() .add("Queuing for resend " + resendNotification.getIdentifier()); notificationsBuffer.add(resendNotification); } logger.debug("resending {} notifications", resendSize); UILogger.getInstance().add("resending {} notifications " + resendSize); delegate.notificationsResent(resendSize); } logger.debug("Monitoring input stream closed by EOF"); UILogger.getInstance().add("Monitoring input stream closed by EOF"); } catch (IOException e) { // An exception when reading the error code is non-critical, it will cause another // retry // sending the message. Other than providing a more stable network connection to // the APNS // server we can't do much about it - so let's not spam the application's error // log. logger.info("Exception while waiting for error code", e); UILogger.getInstance().add("Exception while waiting for error code " + e); delegate.connectionClosed(DeliveryError.UNKNOWN, -1); } finally { close(); drainBuffer(); } } /** * Read a packet like in.readFully(bytes) does - but do not throw an exception and * return false if nothing could be read at all. * * @param in the input stream * @param bytes the array to be filled with data * @return true if a packet as been read, false if the stream was at EOF right at the * beginning. * @throws IOException When a problem occurs, especially EOFException when there's an * EOF in the middle of the packet. */ private boolean readPacket(final InputStream in, final byte[] bytes) throws IOException { final int len = bytes.length; int n = 0; while (n < len) { try { int count = in.read(bytes, n, len - n); if (count < 0) { throw new EOFException("EOF after reading " + n + " bytes of new packet."); } n += count; } catch (IOException ioe) { if (n == 0) return false; throw new IOException("Error after reading " + n + " bytes of packet", ioe); } } return true; } }); t.start(); }
public Thread newThread(Runnable r) { Thread t = DEFAULT.newThread(r); t.setDaemon(true); return t; }
@Override public Thread newThread(Runnable runnable) { Thread thread = backingThreadFactory.newThread(runnable); thread.setName(String.format(nameFormat, count.getAndIncrement())); return thread; }
public Thread newThread(Runnable r) { final Thread th = myDefaultThreadFactory.newThread(r); th.setPriority(Thread.MIN_PRIORITY); return th; }
public Thread newThread(Runnable r) { Thread t = defaultFactory.newThread(r); t.setUncaughtExceptionHandler(handler); return t; }