java.util.concurrent.ScheduledThreadPoolExecutor Java Examples

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor. 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: ZeroCorePoolSize.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example #2
Source File: ExecutionDAOFacade.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Inject
public ExecutionDAOFacade(ExecutionDAO executionDAO, QueueDAO queueDAO, IndexDAO indexDAO,
    RateLimitingDAO rateLimitingDao, PollDataDAO pollDataDAO, ObjectMapper objectMapper, Configuration config) {
    this.executionDAO = executionDAO;
    this.queueDAO = queueDAO;
    this.indexDAO = indexDAO;
    this.rateLimitingDao = rateLimitingDao;
    this.pollDataDAO = pollDataDAO;
    this.objectMapper = objectMapper;
    this.config = config;
    this.scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(4,
        (runnable, executor) -> {
        LOGGER.warn("Request {} to delay updating index dropped in executor {}", runnable, executor);
        Monitors.recordDiscardedIndexingCount("delayQueue");
    });
    this.scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
}
 
Example #3
Source File: ThrottledAsyncChecker.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public ThrottledAsyncChecker(final Timer timer,
                             final long minMsBetweenChecks,
                             final long diskCheckTimeout,
                             final ExecutorService executorService) {
  this.timer = timer;
  this.minMsBetweenChecks = minMsBetweenChecks;
  this.diskCheckTimeout = diskCheckTimeout;
  this.executorService = MoreExecutors.listeningDecorator(executorService);
  this.checksInProgress = new HashMap<>();
  this.completedChecks = new WeakHashMap<>();

  if (this.diskCheckTimeout > 0) {
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new
        ScheduledThreadPoolExecutor(1);
    this.scheduledExecutorService = MoreExecutors
        .getExitingScheduledExecutorService(scheduledThreadPoolExecutor);
  } else {
    this.scheduledExecutorService = null;
  }
}
 
Example #4
Source File: Metrics.java    From vespa with Apache License 2.0 6 votes vote down vote up
private Metrics(Metric metric, Statistics statistics, HealthMonitorConfig healthMonitorConfig,
                ZookeeperServerConfig zkServerConfig, boolean createZkMetricUpdater) {
    this.metric = metric;
    requests = createCounter(METRIC_REQUESTS, statistics);
    failedRequests = createCounter(METRIC_FAILED_REQUESTS, statistics);
    procTimeCounter = createCounter("procTime", statistics);

    if (createZkMetricUpdater) {
        log.log(Level.FINE, "Metric update interval is " + healthMonitorConfig.snapshot_interval() + " seconds");
        long intervalMs = (long) (healthMonitorConfig.snapshot_interval() * 1000);
        executorService = Optional.of(new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory("configserver-metrics")));
        executorService.get().scheduleAtFixedRate(this, 20000, intervalMs, TimeUnit.MILLISECONDS);
        zkMetricUpdater = Optional.of(new ZKMetricUpdater(zkServerConfig, 19500, intervalMs));
    } else {
        executorService = Optional.empty();
        zkMetricUpdater = Optional.empty();
    }
}
 
Example #5
Source File: DnsSrvWatchers.java    From dns-java with Apache License 2.0 6 votes vote down vote up
public DnsSrvWatcher<T> build() {
  checkState(polling ^ dnsSrvWatcherFactory != null, "specify either polling or custom trigger");

  DnsSrvWatcherFactory<T> watcherFactory;
  if (polling) {
    final ScheduledExecutorService executor =
        scheduledExecutorService != null
        ? scheduledExecutorService
        : MoreExecutors.getExitingScheduledExecutorService(
            new ScheduledThreadPoolExecutor(
                1, new ThreadFactoryBuilder().setNameFormat("dns-lookup-%d").build()),
            0, SECONDS);

    watcherFactory =
        cnf -> new PollingDnsSrvWatcher<>(cnf, executor, pollingInterval, pollingIntervalUnit);
  } else {
    watcherFactory = requireNonNull(dnsSrvWatcherFactory, "dnsSrvWatcherFactory");
  }

  final ChangeNotifierFactory<T> changeNotifierFactory =
      fqdn -> new ServiceResolvingChangeNotifier<>(
          resolver, fqdn, resultTransformer, errorHandler);

  return watcherFactory.create(changeNotifierFactory);
}
 
Example #6
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * timed invokeAny(c) throws ExecutionException if no task completes
 */
public void testTimedInvokeAny4() throws Exception {
    final ExecutorService e = new ScheduledThreadPoolExecutor(2);
    try (PoolCleaner cleaner = cleaner(e)) {
        long startTime = System.nanoTime();
        List<Callable<String>> l = new ArrayList<>();
        l.add(new NPETask());
        try {
            e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
            shouldThrow();
        } catch (ExecutionException success) {
            assertTrue(success.getCause() instanceof NullPointerException);
        }
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
}
 
Example #7
Source File: TimerServiceImpl.java    From AlgoTrader with GNU General Public License v2.0 6 votes vote down vote up
private void getScheduledThreadPoolExecutorDaemonThread() {
	timer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
		// set new thread as daemon thread and name appropriately
		public Thread newThread(Runnable r) {
               String uri = engineURI;
               if (engineURI == null)
               {
                   uri = "default";
               }
               Thread t = new Thread(r, "com.espertech.esper.Timer-" + uri + "-" + id);
			//t.setDaemon(true);
			return t;
		}
	});
	timer.setMaximumPoolSize(timer.getCorePoolSize());
}
 
Example #8
Source File: BulkProcessor.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
BulkProcessor(Client client, Listener listener, @Nullable String name, int concurrentRequests, int bulkActions, ByteSizeValue bulkSize, @Nullable TimeValue flushInterval) {
    this.bulkActions = bulkActions;
    this.bulkSize = bulkSize.bytes();

    this.bulkRequest = new BulkRequest();
    this.bulkRequestHandler = concurrentRequests == 0 ?
            new SyncBulkRequestHandler(client, listener) :
            new AsyncBulkRequestHandler(client, listener, concurrentRequests);

    if (flushInterval != null) {
        this.scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, EsExecutors.daemonThreadFactory(client.settings(), (name != null ? "[" + name + "]" : "") + "bulk_processor"));
        this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        this.scheduledFuture = this.scheduler.scheduleWithFixedDelay(new Flush(), flushInterval.millis(), flushInterval.millis(), TimeUnit.MILLISECONDS);
    } else {
        this.scheduler = null;
        this.scheduledFuture = null;
    }
}
 
Example #9
Source File: ScheduledExecutorSubclassTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * getQueue returns the work queue, which contains queued tasks
 */
public void testGetQueue() throws InterruptedException {
    final CountDownLatch done = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor p = new CustomExecutor(1);
    try (PoolCleaner cleaner = cleaner(p, done)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        ScheduledFuture[] tasks = new ScheduledFuture[5];
        for (int i = 0; i < tasks.length; i++) {
            Runnable r = new CheckedRunnable() {
                public void realRun() throws InterruptedException {
                    threadStarted.countDown();
                    await(done);
                }};
            tasks[i] = p.schedule(r, 1, MILLISECONDS);
        }
        await(threadStarted);
        BlockingQueue<Runnable> q = p.getQueue();
        assertTrue(q.contains(tasks[tasks.length - 1]));
        assertFalse(q.contains(tasks[0]));
    }
}
 
Example #10
Source File: JobHistory.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
protected void serviceStart() throws Exception {
  hsManager.start();
  if (storage instanceof Service) {
    ((Service) storage).start();
  }

  scheduledExecutor = new ScheduledThreadPoolExecutor(2,
      new ThreadFactoryBuilder().setNameFormat("Log Scanner/Cleaner #%d")
          .build());

  scheduledExecutor.scheduleAtFixedRate(new MoveIntermediateToDoneRunnable(),
      moveThreadInterval, moveThreadInterval, TimeUnit.MILLISECONDS);

  // Start historyCleaner
  scheduleHistoryCleaner();
  super.serviceStart();
}
 
Example #11
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    mHandler = new Handler();
    LOGD(TAG, "onCreate");
    mCameraSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    setContentView(R.layout.main_activity);
    setupViews();

    // Stores DataItems received by the local broadcaster or from the paired watch.
    mDataItemListAdapter = new DataItemAdapter(this, android.R.layout.simple_list_item_1);
    mDataItemList.setAdapter(mDataItemListAdapter);

    mGeneratorExecutor = new ScheduledThreadPoolExecutor(1);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example #12
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A fixed delay task with overflowing period should not prevent a
 * one-shot task from executing.
 * https://bugs.openjdk.java.net/browse/JDK-8051859
 */
public void testScheduleWithFixedDelay_overflow() throws Exception {
    final CountDownLatch delayedDone = new CountDownLatch(1);
    final CountDownLatch immediateDone = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        final Runnable immediate = new Runnable() { public void run() {
            immediateDone.countDown();
        }};
        final Runnable delayed = new Runnable() { public void run() {
            delayedDone.countDown();
            p.submit(immediate);
        }};
        p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
        await(delayedDone);
        await(immediateDone);
    }
}
 
Example #13
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * getQueue returns the work queue, which contains queued tasks
 */
public void testGetQueue() throws InterruptedException {
    final CountDownLatch done = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p, done)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        ScheduledFuture[] tasks = new ScheduledFuture[5];
        for (int i = 0; i < tasks.length; i++) {
            Runnable r = new CheckedRunnable() {
                public void realRun() throws InterruptedException {
                    threadStarted.countDown();
                    await(done);
                }};
            tasks[i] = p.schedule(r, 1, MILLISECONDS);
        }
        await(threadStarted);
        BlockingQueue<Runnable> q = p.getQueue();
        assertTrue(q.contains(tasks[tasks.length - 1]));
        assertFalse(q.contains(tasks[0]));
    }
}
 
Example #14
Source File: EventQueueWriterTests.java    From Telemetry-Client-for-Android with MIT License 6 votes vote down vote up
@Test
public void sendNormalEvents() {
    CustomStorageHelper fs = new CustomStorageHelper();
    ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
    try {
        for(int i = 0; i < 50; i++) {
            fs.add(EventHelper.generateABCEvent());
        }
    } catch (Exception e) {
    }

    ArrayList<IStorage> storages = new ArrayList<IStorage>();
    storages.add(fs);

    EventQueueWriter eventQueueWriter = new EventQueueWriter(url, storages, new ClientTelemetry(), new ArrayList<ICllEvents>(), new CustomLogger(), scheduledExecutorService);
    eventQueueWriter.setSender(eventSenderOverride);
    eventQueueWriter.run();

    assert(eventSenderOverride.getNumberOfEventsAccepted() == 50);
}
 
Example #15
Source File: MockProvider.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
public MockProvider(URI remoteURI, MockProviderConfiguration configuration, MockRemotePeer context, ProviderFutureFactory futureFactory) {
    this.remoteURI = remoteURI;
    this.configuration = configuration;
    this.context = context;
    this.stats = new MockProviderStats(context != null ? context.getContextStats() : null);
    this.futureFactory = futureFactory;

    serializer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runner) {
            Thread serial = new Thread(runner);
            serial.setDaemon(true);
            serial.setName(MockProvider.this.getClass().getSimpleName() + ":(" +
                           PROVIDER_SEQUENCE.incrementAndGet() + "):[" +
                           getRemoteURI() + "]");
            return serial;
        }
    });

    serializer.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    serializer.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
 
Example #16
Source File: TimedSemaphore.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link TimedSemaphore} and initializes it with
 * an executor service, the given time period, and the limit. The executor
 * service will be used for creating a periodic task for monitoring the time
 * period. It can be <b>null</b>, then a default service will be created.
 *
 * @param service the executor service
 * @param timePeriod the time period
 * @param timeUnit the unit for the period
 * @param limit the limit for the semaphore
 * @throws IllegalArgumentException if the period is less or equals 0
 */
public TimedSemaphore(ScheduledExecutorService service, long timePeriod,
        TimeUnit timeUnit, int limit) {
    if (timePeriod <= 0) {
        throw new IllegalArgumentException("Time period must be greater 0!");
    }

    period = timePeriod;
    unit = timeUnit;

    if (service != null) {
        executorService = service;
        ownExecutor = false;
    } else {
        ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
                THREAD_POOL_SIZE);
        s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        executorService = s;
        ownExecutor = true;
    }

    setLimit(limit);
}
 
Example #17
Source File: ScheduledExecutorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * purge eventually removes cancelled tasks from the queue
 */
public void testPurge() throws InterruptedException {
    final ScheduledFuture[] tasks = new ScheduledFuture[5];
    final Runnable releaser = new Runnable() { public void run() {
        for (ScheduledFuture task : tasks)
            if (task != null) task.cancel(true); }};
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p, releaser)) {
        for (int i = 0; i < tasks.length; i++)
            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
                                  LONG_DELAY_MS, MILLISECONDS);
        int max = tasks.length;
        if (tasks[4].cancel(true)) --max;
        if (tasks[3].cancel(true)) --max;
        // There must eventually be an interference-free point at
        // which purge will not fail. (At worst, when queue is empty.)
        long startTime = System.nanoTime();
        do {
            p.purge();
            long count = p.getTaskCount();
            if (count == max)
                return;
        } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
        fail("Purge failed to remove cancelled tasks");
    }
}
 
Example #18
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * purge eventually removes cancelled tasks from the queue
 */
public void testPurge() throws InterruptedException {
    final ScheduledFuture[] tasks = new ScheduledFuture[5];
    final Runnable releaser = new Runnable() { public void run() {
        for (ScheduledFuture task : tasks)
            if (task != null) task.cancel(true); }};
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p, releaser)) {
        for (int i = 0; i < tasks.length; i++)
            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
                                  LONG_DELAY_MS, MILLISECONDS);
        int max = tasks.length;
        if (tasks[4].cancel(true)) --max;
        if (tasks[3].cancel(true)) --max;
        // There must eventually be an interference-free point at
        // which purge will not fail. (At worst, when queue is empty.)
        long startTime = System.nanoTime();
        do {
            p.purge();
            long count = p.getTaskCount();
            if (count == max)
                return;
        } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
        fail("Purge failed to remove cancelled tasks");
    }
}
 
Example #19
Source File: LazyTraceScheduledThreadPoolExecutor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
LazyTraceScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory,
		RejectedExecutionHandler handler, BeanFactory beanFactory,
		ScheduledThreadPoolExecutor delegate) {
	super(corePoolSize, threadFactory, handler);
	this.beanFactory = beanFactory;
	this.delegate = delegate;
	this.decorateTaskRunnable = ReflectionUtils.findMethod(
			ScheduledThreadPoolExecutor.class, "decorateTask", Runnable.class,
			RunnableScheduledFuture.class);
	makeAccessibleIfNotNull(this.decorateTaskRunnable);
	this.decorateTaskCallable = ReflectionUtils.findMethod(
			ScheduledThreadPoolExecutor.class, "decorateTaskCallable", Callable.class,
			RunnableScheduledFuture.class);
	makeAccessibleIfNotNull(this.decorateTaskCallable);
	this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
			"finalize", null);
	makeAccessibleIfNotNull(this.finalize);
	this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
			"beforeExecute", null);
	makeAccessibleIfNotNull(this.beforeExecute);
	this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
			"afterExecute", null);
	makeAccessibleIfNotNull(this.afterExecute);
	this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
			"terminated");
	makeAccessibleIfNotNull(this.terminated);
	this.newTaskForRunnable = ReflectionUtils.findMethod(
			ScheduledThreadPoolExecutor.class, "newTaskFor", Runnable.class,
			Object.class);
	makeAccessibleIfNotNull(this.newTaskForRunnable);
	this.newTaskForCallable = ReflectionUtils.findMethod(
			ScheduledThreadPoolExecutor.class, "newTaskFor", Callable.class,
			Object.class);
	makeAccessibleIfNotNull(this.newTaskForCallable);
}
 
Example #20
Source File: ThreadPoolBinder.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void monitor(String name, ScheduledThreadPoolExecutor tp, MeterRegistry meterRegistry, Iterable<Tag> tags) {
    FunctionCounter.builder(name + ".completed", tp, ScheduledThreadPoolExecutor::getCompletedTaskCount).tags(tags)
        .description("The approximate total number of tasks that have completed execution").register(meterRegistry);
    Gauge.builder(name + ".active", tp, ScheduledThreadPoolExecutor::getActiveCount).tags(tags)
        .description("The approximate number of threads that are actively executing tasks").register(meterRegistry);
    Gauge.builder(name + ".queued", tp, (tpRef) -> {
        return (double)tpRef.getQueue().size();
    }).tags(tags).description("The approximate number of threads that are queued for execution")
        .register(meterRegistry);
    Gauge.builder(name + ".pool", tp, ScheduledThreadPoolExecutor::getPoolSize).tags(tags)
        .description("The current number of threads in the pool").register(meterRegistry);
}
 
Example #21
Source File: RepairServiceLauncher.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * コンストラクタ. Webコンテナ起動時に呼ばれる。
 */
public RepairServiceLauncher() {
    // 同時起動はしないため、Threadは1つ.
    executor = new ScheduledThreadPoolExecutor(1);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    // リペアツールの実行をスケジュールする.
    RepairAdsService service = new RepairAdsService();
    executor.scheduleWithFixedDelay(service,
            DcCoreConfig.getAdsRepairInitialDelayInSec(),
            DcCoreConfig.getAdsRepairIntervalInSec(),
            TimeUnit.SECONDS);
    logger.info(String.format("RepairAds scheduled with delay interval %d sec.",
            DcCoreConfig.getAdsRepairIntervalInSec()));
}
 
Example #22
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests whether a default executor service is created if no service is
 * provided.
 */
@Test
public void testInitDefaultService() {
    final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
    final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore
            .getExecutorService();
    assertFalse("Wrong periodic task policy", exec
            .getContinueExistingPeriodicTasksAfterShutdownPolicy());
    assertFalse("Wrong delayed task policy", exec
            .getExecuteExistingDelayedTasksAfterShutdownPolicy());
    assertFalse("Already shutdown", exec.isShutdown());
    semaphore.shutdown();
}
 
Example #23
Source File: ConfigReloaderUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testReload_WhenWatchedFilesChange_BadUpdate() throws Exception {
  // set initial conditions for applicationConf and includeFileConf
  String initialLimit = "9000";
  String updatedLimit = "badvalue";
  String applicationConf = createApplicationConf();
  String includedFilePath = modifyIncludeConf(initialLimit);
  File includedFile = new File(includedFilePath);

  ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);

  ConfigReloader<TrivialConfig> reloader = new ConfigReloader<>(executor, TrivialConfig::new);

  TrivialConfig config = reloader.init(applicationConf);
  TrivialState state =
      new TrivialState(config) {
        @Override
        public void fireUpdated() {
          executor.shutdown();
        }
      };

  // check that we successfully read the init'd subject
  assertEquals(Integer.parseInt(initialLimit), config.limit);
  // start watching the include file
  reloader.addWatchFile(includedFile);
  // kick off the subject
  reloader.start(state::update);
  Thread.sleep(5000);
  // modify the watched file
  modifyIncludeConf(updatedLimit);
  Thread.sleep(5000);
  // if something goes wrong with the update we should not change the config (up for debate, the illegal
  // state exceptions are thrown in a different thread, do we want to just trap if we get a invalid config?
  assertEquals(Integer.parseInt(initialLimit), config.limit);
}
 
Example #24
Source File: Shell.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Start the periodic timer when a command is submitted
 */
private void startWatchdog() {
    if (watchdogTimeout == 0) {
        return;
    }
    watchdogCount = 0;
    watchdog = new ScheduledThreadPoolExecutor(1);
    watchdog.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            handleWatchdog();
        }
    }, 1, 1, TimeUnit.SECONDS);
}
 
Example #25
Source File: DrainToFails.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws Throwable {
    testDelayQueue(new DelayQueue());
    testDelayQueue(new ScheduledThreadPoolExecutor(1).getQueue());

    testUnbounded(new LinkedBlockingQueue());
    testUnbounded(new LinkedBlockingDeque());
    testUnbounded(new PriorityBlockingQueue());

    testBounded(new LinkedBlockingQueue(CAPACITY));
    testBounded(new LinkedBlockingDeque(CAPACITY));
    testBounded(new ArrayBlockingQueue(CAPACITY));
}
 
Example #26
Source File: ThreadPoolManager.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected void modified(Map<String, Object> properties) {
    for (Entry<String, Object> entry : properties.entrySet()) {
        if (entry.getKey().equals("service.pid") || entry.getKey().equals("component.id")
                || entry.getKey().equals("component.name")) {
            continue;
        }
        String poolName = entry.getKey();
        Object config = entry.getValue();
        if (config == null) {
            configs.remove(poolName);
        }
        if (config instanceof String) {
            try {
                Integer poolSize = Integer.valueOf((String) config);
                configs.put(poolName, poolSize);
                ThreadPoolExecutor pool = (ThreadPoolExecutor) pools.get(poolName);
                if (pool instanceof ScheduledThreadPoolExecutor) {
                    pool.setCorePoolSize(poolSize);
                    LOGGER.debug("Updated scheduled thread pool '{}' to size {}",
                            new Object[] { poolName, poolSize });
                } else if (pool instanceof QueueingThreadPoolExecutor) {
                    pool.setMaximumPoolSize(poolSize);
                    LOGGER.debug("Updated queuing thread pool '{}' to size {}",
                            new Object[] { poolName, poolSize });
                }
            } catch (NumberFormatException e) {
                LOGGER.warn("Ignoring invalid configuration for pool '{}': {} - value must be an integer",
                        new Object[] { poolName, config });
                continue;
            }
        }
    }
}
 
Example #27
Source File: ThreadPoolManager.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
private ThreadPoolManager() {
	final int instantPoolSize = Math.max(1, ThreadConfig.BASE_THREAD_POOL_SIZE) * Runtime.getRuntime().availableProcessors();

	instantPool = new ThreadPoolExecutor(instantPoolSize, instantPoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100000), new PriorityThreadFactory("InstantPool", ThreadConfig.USE_PRIORITIES ? 7 : Thread.NORM_PRIORITY));
	instantPool.setRejectedExecutionHandler(new AionRejectedExecutionHandler());
	instantPool.prestartAllCoreThreads();

	scheduledPool = new ScheduledThreadPoolExecutor(Math.max(1, ThreadConfig.EXTRA_THREAD_PER_CORE) * Runtime.getRuntime().availableProcessors());
	scheduledPool.setRejectedExecutionHandler(new AionRejectedExecutionHandler());
	scheduledPool.prestartAllCoreThreads();

	longRunningPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
	longRunningPool.setRejectedExecutionHandler(new AionRejectedExecutionHandler());
	longRunningPool.prestartAllCoreThreads();

	WorkStealThreadFactory forkJoinThreadFactory = new WorkStealThreadFactory("ForkJoinPool");
	workStealingPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), forkJoinThreadFactory, new ThreadUncaughtExceptionHandler(), true);
	forkJoinThreadFactory.setDefaultPool(workStealingPool);

	Thread maintainThread = new Thread(new Runnable() {

		@Override
		public void run() {
			purge();
		}
	}, "ThreadPool Purge Task");

	maintainThread.setDaemon(true);
	scheduleAtFixedRate(maintainThread, 150000, 150000);

	log.info("ThreadPoolManager: Initialized with " + scheduledPool.getPoolSize() + " scheduler, " + instantPool.getPoolSize() + " instant, " + longRunningPool.getPoolSize() + " long running, and forking " + workStealingPool.getPoolSize() + " thread(s).");
}
 
Example #28
Source File: CacheClientNotifier.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void addToBlacklistedClient(ClientProxyMembershipID proxyID) {
  blackListedClients.add(proxyID);
  // ensure that cache and distributed system state are current and open
  this.getCache();
  new ScheduledThreadPoolExecutor(1).schedule(
      new ExpireBlackListTask(proxyID), 120, TimeUnit.SECONDS);
}
 
Example #29
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * invokeAny(c) throws ExecutionException if no task completes
 */
public void testInvokeAny4() throws Exception {
    final ExecutorService e = new ScheduledThreadPoolExecutor(2);
    try (PoolCleaner cleaner = cleaner(e)) {
        List<Callable<String>> l = new ArrayList<>();
        l.add(new NPETask());
        try {
            e.invokeAny(l);
            shouldThrow();
        } catch (ExecutionException success) {
            assertTrue(success.getCause() instanceof NullPointerException);
        }
    }
}
 
Example #30
Source File: CacheClientNotifier.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void addToBlacklistedClient(ClientProxyMembershipID proxyID) {
  blackListedClients.add(proxyID);
  // ensure that cache and distributed system state are current and open
  this.getCache();
  new ScheduledThreadPoolExecutor(1).schedule(
      new ExpireBlackListTask(proxyID), 120, TimeUnit.SECONDS);
}