Java Code Examples for java.util.concurrent.ThreadPoolExecutor#DiscardPolicy

The following examples show how to use java.util.concurrent.ThreadPoolExecutor#DiscardPolicy . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * executor using DiscardPolicy drops task if saturated.
 */
public void testSaturatedExecute3() {
    final CountDownLatch done = new CountDownLatch(1);
    final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
    for (int i = 0; i < tasks.length; ++i)
        tasks[i] = new TrackedNoOpRunnable();
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                      LONG_DELAY_MS, MILLISECONDS,
                      new ArrayBlockingQueue<Runnable>(1),
                      new ThreadPoolExecutor.DiscardPolicy());
    try (PoolCleaner cleaner = cleaner(p, done)) {
        p.execute(awaiter(done));

        for (TrackedNoOpRunnable task : tasks)
            p.execute(task);
        for (int i = 1; i < tasks.length; i++)
            assertFalse(tasks[i].done);
    }
    for (int i = 1; i < tasks.length; i++)
        assertFalse(tasks[i].done);
    assertTrue(tasks[0].done); // was waiting in queue
}
 
Example 2
Source File: TestSpatialJoinOperator.java    From presto with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp()
{
    // Before/AfterMethod is chosen here because the executor needs to be shutdown
    // after every single test case to terminate outstanding threads, if any.

    // The line below is the same as newCachedThreadPool(daemonThreadsNamed(...)) except RejectionExecutionHandler.
    // RejectionExecutionHandler is set to DiscardPolicy (instead of the default AbortPolicy) here.
    // Otherwise, a large number of RejectedExecutionException will flood logging, resulting in Travis failure.
    executor = new ThreadPoolExecutor(
            0,
            Integer.MAX_VALUE,
            60L,
            SECONDS,
            new SynchronousQueue<>(),
            daemonThreadsNamed("test-executor-%s"),
            new ThreadPoolExecutor.DiscardPolicy());
    scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s"));
}
 
Example 3
Source File: AstyanaxEventReaderDAO.java    From emodb with Apache License 2.0 6 votes vote down vote up
private static ExecutorService defaultCleanupExecutor(String metricsGroup, LifeCycleRegistry lifeCycle, MetricRegistry metricRegistry) {
    final Meter meter = metricRegistry.meter(MetricRegistry.name(metricsGroup, "AstyanaxEventReaderDAO", "discarded_slab_cleanup"));
    String nameFormat = "Events Slab Reader Cleanup-" + metricsGroup.substring(metricsGroup.lastIndexOf('.') + 1) + "-%d";
    ExecutorService executor = new ThreadPoolExecutor(
            NUM_CLEANUP_THREADS, NUM_CLEANUP_THREADS,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(MAX_CLEANUP_QUEUE_LENGTH),
            new ThreadFactoryBuilder().setNameFormat(nameFormat).build(),
            new ThreadPoolExecutor.DiscardPolicy() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                    meter.mark();
                }
            });
    lifeCycle.manage(new ExecutorServiceManager(executor, Duration.seconds(5), nameFormat));
    return executor;
}
 
Example 4
Source File: HandlerExecutor.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 
 * @param corePoolSize 最小线程数,包括空闲线程
 * @param maxPoolSize 最大线程数 
 * @param keepAliveTime 当线程数大于核心时,终止多余的空闲线程等待新任务的最长时间
 * @param cacheSize 执行队列大小
 * @param prefix 线程池前缀名称
 */
public HandlerExecutor(int corePoolSize, int maxPoolSize, int keepAliveTime, int cacheSize, String prefix) {
	TimeUnit unit = TimeUnit.MINUTES;
	/**
	 * 任务队列
	 */
	LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
	/**
	 * 队例满到无法接受新任务时。直接抛弃
	 */
	RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
	
	if (prefix == null) {
		prefix = "";
	}
	ThreadFactory threadFactory = new HandlerThreadFactory(prefix);
	pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
 
Example 5
Source File: MysqlChannel.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public MysqlChannel(Mysql mysql, SyncerOutputMeta outputMeta, Ack ack) {
  MysqlConnection connection = mysql.getConnection();
  jdbcTemplate = new JdbcTemplate(connection.dataSource());
  batchBuffer = new BatchBuffer<>(mysql.getBatch());
  sqlMapper = new NestedSQLMapper(mysql.getRowMapping(), jdbcTemplate);
  this.batch = mysql.getBatch();
  this.ack = ack;
  FailureLogConfig failureLog = mysql.getFailureLog();
  sqlFailureLog = FailureLog.getLogger(Paths.get(outputMeta.getFailureLogDir(), connection.connectionIdentifier()),
      failureLog, new TypeToken<FailureEntry<SyncWrapper<String>>>() {
      });
  output = connection.connectionIdentifier();
  consumerId = mysql.getConsumerId();
  mysqlService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
      new ArrayBlockingQueue<>(10),
      new NamedThreadFactory("syncer-" + connection.connectionIdentifier() + "-output-mysql"),
      new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 6
Source File: LockManager.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
public LockManager(RxSession session) {
    this.session = session;
    acquireLock = session.getSession().prepare(
            "UPDATE locks USING TTL ? SET value = ? WHERE name = ? IF value IN (NULL, ?)");
    releaseLock = session.getSession().prepare(
            "UPDATE locks SET value = NULL WHERE name = ? IF value = ?");
    renewLock = session.getSession().prepare(
            "UPDATE locks USING TTL ? SET value = ? WHERE name = ? IF value = ?");
    getTTL = session.getSession().prepare("SELECT TTL(value) FROM locks WHERE name = ?");

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("locks-thread-pool-%d").build();
    locksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory, new ThreadPoolExecutor.DiscardPolicy());

    activeLocks = new HashMap<>();
    activeLocksLock = new ReentrantReadWriteLock();

    locksExecutor.scheduleAtFixedRate(this::renewLocks, 0, LOCK_RENEWAL_RATE, TimeUnit.SECONDS);
}
 
Example 7
Source File: DefaultUpnpServiceConfiguration.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public ClingExecutor() {
    this(new ClingThreadFactory(),
         new ThreadPoolExecutor.DiscardPolicy() {
             // The pool is unbounded but rejections will happen during shutdown
             @Override
             public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
                 // Log and discard
                 log.info("Thread pool rejected execution of " + runnable.getClass());
                 super.rejectedExecution(runnable, threadPoolExecutor);
             }
         }
    );
}
 
Example 8
Source File: BesuUpnpServiceConfiguration.java    From besu with Apache License 2.0 5 votes vote down vote up
private BesuUpnpServiceConfiguration(
    final int streamListenPort, final int multicastResponsePort) {
  executorService =
      new ThreadPoolExecutor(
          16,
          200,
          10,
          TimeUnit.SECONDS,
          new ArrayBlockingQueue<>(2000),
          new DefaultUpnpServiceConfiguration.JUPnPThreadFactory(),
          new ThreadPoolExecutor.DiscardPolicy() {
            // The pool is bounded and rejections will happen during shutdown
            @Override
            public void rejectedExecution(
                final Runnable runnable, final ThreadPoolExecutor threadPoolExecutor) {
              // Log and discard
              LOG.warn("Thread pool rejected execution of " + runnable.getClass());
              super.rejectedExecution(runnable, threadPoolExecutor);
            }
          });
  executorService.allowCoreThreadTimeOut(true);

  deviceDescriptorBinderUDA10 = new UDA10DeviceDescriptorBinderImpl();
  serviceDescriptorBinderUDA10 = new UDA10ServiceDescriptorBinderImpl();
  namespace = new Namespace();

  this.streamListenPort = streamListenPort;
  this.multicastResponsePort = multicastResponsePort;
}
 
Example 9
Source File: NimTaskExecutor.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
private ExecutorService createExecutor(Config config) {
    ThreadPoolExecutor service = new ThreadPoolExecutor(config.core, config.max, config.timeout,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(QUEUE_INIT_CAPACITY),
            new TaskThreadFactory(name), new ThreadPoolExecutor.DiscardPolicy());

    allowCoreThreadTimeOut(service, config.allowCoreTimeOut);

    return service;
}
 
Example 10
Source File: TaskExecutor.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
private ExecutorService createExecutor(Config config) {
    ThreadPoolExecutor service = new ThreadPoolExecutor(config.core, config.max, config.timeout,
            TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(QUEUE_INIT_CAPACITY, mQueueComparator),
            new TaskThreadFactory(name), new ThreadPoolExecutor.DiscardPolicy());

    allowCoreThreadTimeOut(service, config.allowCoreTimeOut);

    return service;
}
 
Example 11
Source File: AbstractTwillService.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
protected final void startUp() throws Exception {
  // Single thread executor that will discard task silently if it is already terminated, which only
  // happens when this service is shutting down.
  messageCallbackExecutor = new ThreadPoolExecutor(1, 1,
                                                   0L, TimeUnit.MILLISECONDS,
                                                   new LinkedBlockingQueue<Runnable>(),
                                                   Threads.createDaemonThreadFactory("message-callback"),
                                                   new ThreadPoolExecutor.DiscardPolicy());

  // Watch for session expiration, recreate the live node if reconnected after expiration.
  watcherCancellable = zkClient.addConnectionWatcher(new Watcher() {
    private boolean expired = false;

    @Override
    public void process(WatchedEvent event) {
      if (event.getState() == Event.KeeperState.Expired) {
        LOG.warn("ZK Session expired for service {} with runId {}.", getServiceName(), runId.getId());
        expired = true;
      } else if (event.getState() == Event.KeeperState.SyncConnected && expired) {
        LOG.info("Reconnected after expiration for service {} with runId {}", getServiceName(), runId.getId());
        expired = false;
        logIfFailed(createLiveNode());
      }
    }
  });

  // Create the live node, if succeeded, start the service, otherwise fail out.
  createLiveNode().get();

  // Create node for messaging
  ZKOperations.ignoreError(zkClient.create(getZKPath("messages"), null, CreateMode.PERSISTENT),
                           KeeperException.NodeExistsException.class, null).get();

  doStart();

  // Starts watching for messages
  watchMessages();
}
 
Example 12
Source File: ZkRouteParser.java    From sumk with Apache License 2.0 5 votes vote down vote up
private ZkRouteParser(String zkUrl) {
	this.zkUrl = zkUrl;
	String temp = AppInfo.getLatin("sumk.rpc.server.includes");
	includes = StringUtil.isEmpty(temp) ? null : Matchers.createWildcardMatcher(temp, 1);

	temp = AppInfo.getLatin("sumk.rpc.server.excludes");
	excludes = StringUtil.isEmpty(temp) ? null : Matchers.createWildcardMatcher(temp, 1);
	executor = new ThreadPoolExecutor(1, 1, 5000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10000),
			SumkThreadPool.createThreadFactory("rpc-client-"), new ThreadPoolExecutor.DiscardPolicy());
	executor.allowCoreThreadTimeOut(true);
}
 
Example 13
Source File: MostExecutors.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
  return new ThreadPoolExecutor(
      /* corePoolSize */ 1,
      /* maximumPoolSize */ 1,
      /* keepAliveTime */ 0L,
      TimeUnit.MILLISECONDS,
      /* workQueue */ new LinkedBlockingQueue<Runnable>(),
      /* threadFactory */ threadFactory,
      /* handler */ new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 14
Source File: HttpCmdAcceptor.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public HttpCmdAcceptor(ServerSocket serverSocket, HttpCmdContext context) {
    this.context = context;
    this.serverSocket = serverSocket;
    this.executorService = new ThreadPoolExecutor(Constants.AVAILABLE_PROCESSOR,
            Constants.AVAILABLE_PROCESSOR,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(100), new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 15
Source File: MostExecutors.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ExecutorService newMultiThreadExecutor(ThreadFactory threadFactory, int count) {
  return new ThreadPoolExecutor(
      /* corePoolSize */ count,
      /* maximumPoolSize */ count,
      /* keepAliveTime */ 0L,
      TimeUnit.MILLISECONDS,
      /* workQueue */ new LinkedBlockingQueue<Runnable>(),
      /* threadFactory */ threadFactory,
      /* handler */ new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 16
Source File: ClientAppRegisterClientController.java    From radar with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() {
	threadSize = soaConfig.getRegisterClientThreadSize();		
	executor = new ThreadPoolExecutor(threadSize+1,threadSize+1,3L,TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), SoaThreadFactory.create("registerClient", true),new ThreadPoolExecutor.DiscardPolicy());
	executor.execute(() -> {
		registerClient();
	});
}
 
Example 17
Source File: StatusResponseManager.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Create a StatusResponseManager with default parameters.
 */
StatusResponseManager() {
    int cap = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheSize",
                DEFAULT_CACHE_SIZE));
    cacheCapacity = cap > 0 ? cap : 0;

    int life = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheLifetime",
                DEFAULT_CACHE_LIFETIME));
    cacheLifetime = life > 0 ? life : 0;

    String uriStr = GetPropertyAction
            .privilegedGetProperty("jdk.tls.stapling.responderURI");
    URI tmpURI;
    try {
        tmpURI = ((uriStr != null && !uriStr.isEmpty()) ?
                new URI(uriStr) : null);
    } catch (URISyntaxException urise) {
        tmpURI = null;
    }
    defaultResponder = tmpURI;

    respOverride = GetBooleanAction
            .privilegedGetProperty("jdk.tls.stapling.responderOverride");
    ignoreExtensions = GetBooleanAction
            .privilegedGetProperty("jdk.tls.stapling.ignoreExtensions");

    threadMgr = new ScheduledThreadPoolExecutor(DEFAULT_CORE_THREADS,
            new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    }, new ThreadPoolExecutor.DiscardPolicy());
    threadMgr.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    threadMgr.setContinueExistingPeriodicTasksAfterShutdownPolicy(
            false);
    threadMgr.setKeepAliveTime(5000, TimeUnit.MILLISECONDS);
    threadMgr.allowCoreThreadTimeOut(true);
    responseCache = Cache.newSoftMemoryCache(
            cacheCapacity, cacheLifetime);
}
 
Example 18
Source File: FlusherPool.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public FlusherPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
    this.threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
            new ArrayBlockingQueue<Runnable>(1024), new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 19
Source File: ClusterNameServiceExecutorService.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
protected void validate() throws Exception {
    this.executorService = new ThreadPoolExecutor(config.getTopicDynamicMetadataBatchMinThreads(), config.getTopicDynamicMetadataBatchMaxThreads(),
            config.getTopicDynamicMetadataBatchKeepalive(), TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(config.getTopicDynamicMetadataBatchQueueSize()),
            new NamedThreadFactory("joyqueue-cluster-nameservice-threads"), new ThreadPoolExecutor.DiscardPolicy());
}
 
Example 20
Source File: StatusResponseManager.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a StatusResponseManager with default parameters.
 */
StatusResponseManager() {
    int cap = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheSize",
                DEFAULT_CACHE_SIZE));
    cacheCapacity = cap > 0 ? cap : 0;

    int life = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheLifetime",
                DEFAULT_CACHE_LIFETIME));
    cacheLifetime = life > 0 ? life : 0;

    String uriStr = GetPropertyAction
            .privilegedGetProperty("jdk.tls.stapling.responderURI");
    URI tmpURI;
    try {
        tmpURI = ((uriStr != null && !uriStr.isEmpty()) ?
                new URI(uriStr) : null);
    } catch (URISyntaxException urise) {
        tmpURI = null;
    }
    defaultResponder = tmpURI;

    respOverride = AccessController.doPrivileged(
            new GetBooleanAction("jdk.tls.stapling.responderOverride"));
    ignoreExtensions = AccessController.doPrivileged(
            new GetBooleanAction("jdk.tls.stapling.ignoreExtensions"));

    threadMgr = new ScheduledThreadPoolExecutor(DEFAULT_CORE_THREADS,
            new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    }, new ThreadPoolExecutor.DiscardPolicy());
    threadMgr.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    threadMgr.setContinueExistingPeriodicTasksAfterShutdownPolicy(
            false);
    threadMgr.setKeepAliveTime(5000, TimeUnit.MILLISECONDS);
    threadMgr.allowCoreThreadTimeOut(true);
    responseCache = Cache.newSoftMemoryCache(
            cacheCapacity, cacheLifetime);
}