Java Code Examples for java.util.concurrent.ScheduledThreadPoolExecutor#schedule()
The following examples show how to use
java.util.concurrent.ScheduledThreadPoolExecutor#schedule() .
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: ScheduledExecutorTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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 2
Source File: ZeroCoreThreads.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
void test(ScheduledThreadPoolExecutor p) throws Throwable { Runnable dummy = new Runnable() { public void run() { throw new AssertionError("shouldn't get here"); }}; BlockingQueue q = p.getQueue(); ReentrantLock lock = getField(q, "lock"); Condition available = getField(q, "available"); equal(0, p.getPoolSize()); equal(0, p.getLargestPoolSize()); equal(0L, p.getTaskCount()); equal(0L, p.getCompletedTaskCount()); p.schedule(dummy, 1L, HOURS); // Ensure one pool thread actually waits in timed queue poll awaitHasWaiters(lock, available, LONG_DELAY_MS); equal(1, p.getPoolSize()); equal(1, p.getLargestPoolSize()); equal(1L, p.getTaskCount()); equal(0L, p.getCompletedTaskCount()); }
Example 3
Source File: DelayOverflow.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
void scheduleAtTheEndOfTime(ScheduledThreadPoolExecutor pool, Runnable r, int how) { switch (how) { case 0: pool.schedule(r, Long.MAX_VALUE, MILLISECONDS); break; case 1: pool.schedule(Executors.callable(r), Long.MAX_VALUE, DAYS); break; case 2: pool.scheduleWithFixedDelay(r, Long.MAX_VALUE, 1000, NANOSECONDS); break; case 3: pool.scheduleAtFixedRate(r, Long.MAX_VALUE, 1000, MILLISECONDS); break; default: fail(String.valueOf(how)); } }
Example 4
Source File: ScheduledExecutorTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * delayed schedule of callable successfully executes after delay */ public void testSchedule1() throws Exception { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); Callable task = new CheckedCallable<Boolean>() { public Boolean realCall() { done.countDown(); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); return Boolean.TRUE; }}; Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); assertSame(Boolean.TRUE, f.get()); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); assertTrue(done.await(0L, MILLISECONDS)); } }
Example 5
Source File: ScheduledExecutorSubclassTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: ZeroCorePoolSize.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
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 7
Source File: ScheduledExecutorTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * delayed schedule of callable successfully executes after delay */ public void testSchedule1() throws Exception { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); Callable task = new CheckedCallable<Boolean>() { public Boolean realCall() { done.countDown(); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); return Boolean.TRUE; }}; Future f = p.schedule(task, timeoutMillis(), MILLISECONDS); assertSame(Boolean.TRUE, f.get()); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); assertTrue(done.await(0L, MILLISECONDS)); } }
Example 8
Source File: ZeroCorePoolSize.java From hottub with GNU General Public License v2.0 | 6 votes |
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 9
Source File: DelayOverflow.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
void scheduleNow(ScheduledThreadPoolExecutor pool, Runnable r, int how) { switch (how) { case 0: pool.schedule(r, 0, MILLISECONDS); break; case 1: pool.schedule(Executors.callable(r), 0, DAYS); break; case 2: pool.scheduleWithFixedDelay(r, 0, 1000, NANOSECONDS); break; case 3: pool.scheduleAtFixedRate(r, 0, 1000, MILLISECONDS); break; default: fail(String.valueOf(how)); } }
Example 10
Source File: OrienteerFilter.java From Orienteer with Apache License 2.0 | 5 votes |
/** * Reload Orienteer with delay and wait * @param delay - delay in ms. After delay Orienteer will be reload * @param wait - wait in ms. Wait before {@link OrienteerFilter} starts reload */ public static void reloadOrienteer(long delay, final long wait) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); executor.schedule(() -> { try { instance.reload(wait); } catch (ServletException e) { LOG.error("Can't reload Orienteer", e); } }, delay, TimeUnit.MILLISECONDS); }
Example 11
Source File: ScheduledExecutorTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * schedule throws RejectedExecutionException if shutdown */ public void testSchedule2_RejectedExecutionException() throws InterruptedException { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); p.schedule(new NoOpCallable(), MEDIUM_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (RejectedExecutionException success) { } catch (SecurityException ok) {} } }
Example 12
Source File: ScheduledExecutorTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * execute throws RejectedExecutionException if shutdown */ public void testSchedule1_RejectedExecutionException() throws InterruptedException { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { p.shutdown(); p.schedule(new NoOpRunnable(), MEDIUM_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (RejectedExecutionException success) { } catch (SecurityException ok) {} } }
Example 13
Source File: ScheduledExecutorTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * schedule(null) throws NPE */ public void testScheduleNull() throws InterruptedException { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { try { TrackedCallable callable = null; Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (NullPointerException success) {} } }
Example 14
Source File: TestNonBlockingReads.java From distributedlog with Apache License 2.0 | 5 votes |
@Test(timeout = 100000) public void testNonBlockingReadRecovery() throws Exception { String name = "distrlog-non-blocking-reader-recovery"; final DistributedLogConfiguration confLocal = new DistributedLogConfiguration(); confLocal.loadConf(conf); confLocal.setReadAheadBatchSize(10); confLocal.setReadAheadMaxRecords(10); final DistributedLogManager dlm = createNewDLM(confLocal, name); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); ScheduledFuture writerClosedFuture = null; try { final Thread currentThread = Thread.currentThread(); writerClosedFuture = executor.schedule( new Runnable() { @Override public void run() { try { writeRecordsForNonBlockingReads(confLocal, dlm, true); } catch (Exception exc) { currentThread.interrupt(); } } }, 100, TimeUnit.MILLISECONDS); readNonBlocking(dlm, false); assertFalse(currentThread.isInterrupted()); } finally { if (writerClosedFuture != null){ // ensure writer.closeAndComplete is done before we close dlm writerClosedFuture.get(); } executor.shutdown(); dlm.close(); } }
Example 15
Source File: EurekaBeatReactor.java From nacos-sync with Apache License 2.0 | 5 votes |
public EurekaBeatReactor(EurekaHttpClient eurekaHttpClient) { this.eurekaHttpClient = eurekaHttpClient; executorService = new ScheduledThreadPoolExecutor(30, r -> { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName("com.alibaba.nacossync.eureka.beat.sender"); return thread; }); executorService.schedule(new BeatProcessor(), 0, TimeUnit.SECONDS); }
Example 16
Source File: StickyKeyModeImpl.java From buffer_bci with GNU General Public License v3.0 | 5 votes |
/** * The reset in StickyMode is responsible for: * 1) Making sure to keep some delay in between two commands such that GDX system registers it as * command. * 2) If no new command is registered, Set last command as current command after a pre-defined delay. * */ @Override public void reset() { startLastCommandWatchDog(); setGdxCommand(Input.Keys.UNKNOWN); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); if (!newCommandRegistered) executor.schedule(() -> setGdxCommand(lastGdxCommand), StandardizedInterface.KEY_REPLACER_TIME_TO_WAIT_BETWEEN_TWO_COMMANDS, TimeUnit.MILLISECONDS); }
Example 17
Source File: ScheduledExecutorTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * remove(task) removes queued task, and fails to remove active task */ public void testRemove() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p, done)) { ScheduledFuture[] tasks = new ScheduledFuture[5]; final CountDownLatch threadStarted = new CountDownLatch(1); 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(); assertFalse(p.remove((Runnable)tasks[0])); assertTrue(q.contains((Runnable)tasks[4])); assertTrue(q.contains((Runnable)tasks[3])); assertTrue(p.remove((Runnable)tasks[4])); assertFalse(p.remove((Runnable)tasks[4])); assertFalse(q.contains((Runnable)tasks[4])); assertTrue(q.contains((Runnable)tasks[3])); assertTrue(p.remove((Runnable)tasks[3])); assertFalse(q.contains((Runnable)tasks[3])); } }
Example 18
Source File: RedisFeatureSinkTest.java From feast with Apache License 2.0 | 4 votes |
@Test(timeout = 10000) public void shouldRetryFailConnection() throws InterruptedException { RedisConfig redisConfig = RedisConfig.newBuilder() .setHost(REDIS_HOST) .setPort(REDIS_PORT) .setMaxRetries(4) .setInitialBackoffMs(2000) .build(); redisFeatureSink = redisFeatureSink .toBuilder() .setRedisConfig(redisConfig) .build() .withSpecsView(redisFeatureSink.getSpecsView()); HashMap<RedisKey, FeatureRow> kvs = new LinkedHashMap<>(); kvs.put( RedisKey.newBuilder() .setFeatureSet("myproject/fs") .addEntities(field("entity", 1, Enum.INT64)) .build(), FeatureRow.newBuilder() .setEventTimestamp(Timestamp.getDefaultInstance()) .addFields(Field.newBuilder().setValue(Value.newBuilder().setStringVal("one"))) .build()); List<FeatureRow> featureRows = ImmutableList.of( FeatureRow.newBuilder() .setFeatureSet("myproject/fs") .addFields(field("entity", 1, Enum.INT64)) .addFields(field("feature", "one", Enum.STRING)) .build()); PCollection<Long> failedElementCount = p.apply(Create.of(featureRows)) .apply(redisFeatureSink.writer()) .getFailedInserts() .apply(Window.<FailedElement>into(new GlobalWindows()).triggering(Never.ever())) .apply(Count.globally()); redis.stop(); final ScheduledThreadPoolExecutor redisRestartExecutor = new ScheduledThreadPoolExecutor(1); ScheduledFuture<?> scheduledRedisRestart = redisRestartExecutor.schedule( () -> { redis.start(); }, 3, TimeUnit.SECONDS); PAssert.that(failedElementCount).containsInAnyOrder(0L); p.run(); scheduledRedisRestart.cancel(true); kvs.forEach( (key, value) -> { byte[] actual = sync.get(key.toByteArray()); assertThat(actual, equalTo(value.toByteArray())); }); }
Example 19
Source File: MemoryDuplicateChecker.java From wechat-sdk with Apache License 2.0 | 4 votes |
private void checkClearThreadStarted() { if (!clearThreadStarted.getAndSet(true)) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); executor.schedule(new ClearTask(), clearPeriod, TimeUnit.SECONDS); } }
Example 20
Source File: TransactionalityTest.java From quantumdb with Apache License 2.0 | 4 votes |
@Test public void crossTest() throws ExecutionException, InterruptedException, SQLException { log.info("Starting cross test..."); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); Future<?> future = executor.schedule(() -> { try (Connection conn1 = database.createConnection()) { log.info("Updating all records in source table in reversed order..."); for (int id = ROWS; id > 0; id--) { try (Statement statement = conn1.createStatement()) { statement.execute("UPDATE source SET name = 'Michael de Jong' WHERE id = " + id); Thread.sleep(10); } log.info("Updated id: " + id); } } catch (SQLException | InterruptedException e) { log.error("Error while updating records in source table: " + e.getMessage(), e); } }, 5, TimeUnit.SECONDS); log.info("Running migration of records from source to target table..."); int lastId = 0; Connection connection = database.getConnection(); while (true) { try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery("SELECT * FROM " + MIGRATE_FUNCTION + "(" + lastId + ");"); if (resultSet.next()) { int result = resultSet.getInt(1); if (result > lastId) { log.info("Migrated up until id: " + lastId); lastId = result; continue; } } break; } } log.info("Awaiting termination of updater thread..."); future.get(); log.info("Verifying consistency between source and target table..."); verifyConsistencyTables(connection); }