List of usage examples for java.util.concurrent ScheduledExecutorService schedule
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
From source file:org.apache.hadoop.hdfs.TestDFSInotifyEventInputStream.java
@Test(timeout = 120000) public void testReadEventsWithTimeout() throws IOException, InterruptedException, MissingEventsException { Configuration conf = new HdfsConfiguration(); MiniQJMHACluster cluster = new MiniQJMHACluster.Builder(conf).build(); try {//from w ww . jav a2 s .c om cluster.getDfsCluster().waitActive(); cluster.getDfsCluster().transitionToActive(0); final DFSClient client = new DFSClient(cluster.getDfsCluster().getNameNode(0).getNameNodeAddress(), conf); DFSInotifyEventInputStream eis = client.getInotifyEventStream(); ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor(); ex.schedule(new Runnable() { @Override public void run() { try { client.mkdirs("/dir", null, false); } catch (IOException e) { // test will fail LOG.error("Unable to create /dir", e); } } }, 1, TimeUnit.SECONDS); // a very generous wait period -- the edit will definitely have been // processed by the time this is up EventBatch batch = eis.poll(5, TimeUnit.SECONDS); Assert.assertNotNull(batch); Assert.assertEquals(1, batch.getEvents().length); Assert.assertTrue(batch.getEvents()[0].getEventType() == Event.EventType.CREATE); Assert.assertEquals("/dir", ((Event.CreateEvent) batch.getEvents()[0]).getPath()); } finally { cluster.shutdown(); } }
From source file:org.apache.hadoop.hbase.test.IntegrationTestTimeBoundedRequestsWithRegionReplicas.java
@Override protected void runIngestTest(long defaultRunTime, long keysPerServerPerIter, int colsPerKey, int recordSize, int writeThreads, int readThreads) throws Exception { LOG.info("Cluster size:" + util.getHBaseClusterInterface().getClusterStatus().getServersSize()); long start = System.currentTimeMillis(); String runtimeKey = String.format(RUN_TIME_KEY, this.getClass().getSimpleName()); long runtime = util.getConfiguration().getLong(runtimeKey, defaultRunTime); long startKey = 0; long numKeys = getNumKeys(keysPerServerPerIter); // write data once LOG.info("Writing some data to the table"); writeData(colsPerKey, recordSize, writeThreads, startKey, numKeys); // flush the table LOG.info("Flushing the table"); Admin admin = util.getHBaseAdmin();/*from www . j a v a2 s. c om*/ admin.flush(getTablename()); // re-open the regions to make sure that the replicas are up to date long refreshTime = conf.getLong(StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, 0); if (refreshTime > 0 && refreshTime <= 10000) { LOG.info("Sleeping " + refreshTime + "ms to ensure that the data is replicated"); Threads.sleep(refreshTime * 3); } else { LOG.info("Reopening the table"); admin.disableTable(getTablename()); admin.enableTable(getTablename()); } // We should only start the ChaosMonkey after the readers are started and have cached // all of the region locations. Because the meta is not replicated, the timebounded reads // will timeout if meta server is killed. // We will start the chaos monkey after 1 minute, and since the readers are reading random // keys, it should be enough to cache every region entry. long chaosMonkeyDelay = conf.getLong(String.format("%s.%s", TEST_NAME, CHAOS_MONKEY_DELAY_KEY), DEFAUL_CHAOS_MONKEY_DELAY); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); LOG.info(String.format("ChaosMonkey delay is : %d seconds. Will start %s " + "ChaosMonkey after delay", chaosMonkeyDelay / 1000, monkeyToUse)); ScheduledFuture<?> result = executorService.schedule(new Runnable() { @Override public void run() { try { LOG.info("Starting ChaosMonkey"); monkey.start(); monkey.waitForStop(); } catch (Exception e) { LOG.warn(StringUtils.stringifyException(e)); } } }, chaosMonkeyDelay, TimeUnit.MILLISECONDS); // set the intended run time for the reader. The reader will do read requests // to random keys for this amount of time. long remainingTime = runtime - (System.currentTimeMillis() - start); LOG.info("Reading random keys from the table for " + remainingTime / 60000 + " min"); this.conf.setLong(String.format(RUN_TIME_KEY, TimeBoundedMultiThreadedReader.class.getSimpleName()), remainingTime); // load tool shares the same conf // now start the readers which will run for configured run time try { int ret = loadTool .run(getArgsForLoadTestTool("-read", String.format("100:%d", readThreads), startKey, numKeys)); if (0 != ret) { String errorMsg = "Verification failed with error code " + ret; LOG.error(errorMsg); Assert.fail(errorMsg); } } finally { if (result != null) result.cancel(false); monkey.stop("Stopping the test"); monkey.waitForStop(); executorService.shutdown(); } }
From source file:com.github.ambry.utils.UtilsTest.java
/** * Test {@link Utils#newScheduler(int, String, boolean)} *//*from w w w. j a va2 s . c om*/ @Test public void newSchedulerTest() throws Exception { ScheduledExecutorService scheduler = Utils.newScheduler(2, false); Future<String> future = scheduler.schedule(new Callable<String>() { @Override public String call() { return Thread.currentThread().getName(); } }, 50, TimeUnit.MILLISECONDS); String threadName = future.get(10, TimeUnit.SECONDS); assertTrue("Unexpected thread name returned: " + threadName, threadName.startsWith("ambry-scheduler-")); scheduler.shutdown(); }
From source file:com.networknt.client.Client.java
private void checkCCTokenExpired() throws ClientException, ApiException { long tokenRenewBeforeExpired = (Integer) oauthConfig.get(TOKEN_RENEW_BEFORE_EXPIRED); long expiredRefreshRetryDelay = (Integer) oauthConfig.get(EXPIRED_REFRESH_RETRY_DELAY); long earlyRefreshRetryDelay = (Integer) oauthConfig.get(EARLY_REFRESH_RETRY_DELAY); boolean isInRenewWindow = expire - System.currentTimeMillis() < tokenRenewBeforeExpired; logger.trace("isInRenewWindow = " + isInRenewWindow); if (isInRenewWindow) { if (expire <= System.currentTimeMillis()) { logger.trace("In renew window and token is expired."); // block other request here to prevent using expired token. synchronized (Client.class) { if (expire <= System.currentTimeMillis()) { logger.trace("Within the synch block, check if the current request need to renew token"); if (!renewing || System.currentTimeMillis() > expiredRetryTimeout) { // if there is no other request is renewing or the renewing flag is true but renewTimeout is passed renewing = true; expiredRetryTimeout = System.currentTimeMillis() + expiredRefreshRetryDelay; logger.trace(/* w w w .ja va2s .com*/ "Current request is renewing token synchronously as token is expired already"); getCCToken(); renewing = false; } else { logger.trace("Circuit breaker is tripped and not timeout yet!"); // reject all waiting requests by thrown an exception. throw new ApiException(new Status(STATUS_CLIENT_CREDENTIALS_TOKEN_NOT_AVAILABLE)); } } } } else { // Not expired yet, try to renew async but let requests use the old token. logger.trace("In renew window but token is not expired yet."); synchronized (Client.class) { if (expire > System.currentTimeMillis()) { if (!renewing || System.currentTimeMillis() > earlyRetryTimeout) { renewing = true; earlyRetryTimeout = System.currentTimeMillis() + earlyRefreshRetryDelay; logger.trace("Retrieve token async is called while token is not expired yet"); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.schedule(new Runnable() { @Override public void run() { try { getCCToken(); renewing = false; logger.trace("Async get token is completed."); } catch (Exception e) { logger.error("Async retrieve token error", e); // swallow the exception here as it is on a best effort basis. } } }, 50, TimeUnit.MILLISECONDS); executor.shutdown(); } } } } } logger.trace("Check secondary token is done!"); }
From source file:org.elasticsearch.client.sniff.SnifferTests.java
@SuppressWarnings("unchecked") public void testDefaultSchedulerSchedule() { RestClient restClient = mock(RestClient.class); HostsSniffer hostsSniffer = mock(HostsSniffer.class); Scheduler noOpScheduler = new Scheduler() { @Override//from w w w .j ava 2 s .c o m public Future<?> schedule(Sniffer.Task task, long delayMillis) { return mock(Future.class); } @Override public void shutdown() { } }; Sniffer sniffer = new Sniffer(restClient, hostsSniffer, noOpScheduler, 0L, 0L); Sniffer.Task task = sniffer.new Task(randomLongBetween(1, Long.MAX_VALUE)); ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class); final ScheduledFuture<?> mockedFuture = mock(ScheduledFuture.class); when(scheduledExecutorService.schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class))) .then(new Answer<ScheduledFuture<?>>() { @Override public ScheduledFuture<?> answer(InvocationOnMock invocationOnMock) { return mockedFuture; } }); DefaultScheduler scheduler = new DefaultScheduler(scheduledExecutorService); long delay = randomLongBetween(1, Long.MAX_VALUE); Future<?> future = scheduler.schedule(task, delay); assertSame(mockedFuture, future); verify(scheduledExecutorService).schedule(task, delay, TimeUnit.MILLISECONDS); verifyNoMoreInteractions(scheduledExecutorService, mockedFuture); }
From source file:net.dv8tion.jda.core.requests.RestAction.java
/** * Schedules a call to {@link #complete()} to be executed after the specified {@code delay}. * <br>This is an <b>asynchronous</b> operation that will return a * {@link java.util.concurrent.ScheduledFuture ScheduledFuture} representing the task. * * <p>The returned Future will provide the return type of a {@link #complete()} operation when * received through the <b>blocking</b> call to {@link java.util.concurrent.Future#get()}! * * <p>The specified {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} is used for this operation. * * @param delay//from www.j av a 2s. c o m * The delay after which this computation should be executed, negative to execute immediately * @param unit * The {@link java.util.concurrent.TimeUnit TimeUnit} to convert the specified {@code delay} * @param executor * The Non-null {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} that should be used * to schedule this operation * * @throws java.lang.IllegalArgumentException * If the provided TimeUnit or ScheduledExecutorService is {@code null} * * @return {@link java.util.concurrent.ScheduledFuture ScheduledFuture} * representing the delayed operation */ public ScheduledFuture<T> submitAfter(long delay, TimeUnit unit, ScheduledExecutorService executor) { Checks.notNull(executor, "Scheduler"); Checks.notNull(unit, "TimeUnit"); return executor.schedule((Callable<T>) this::complete, delay, unit); }
From source file:net.dv8tion.jda.core.requests.RestAction.java
/** * Schedules a call to {@link #queue(java.util.function.Consumer, java.util.function.Consumer)} * to be executed after the specified {@code delay}. * <br>This is an <b>asynchronous</b> operation that will return a * {@link java.util.concurrent.ScheduledFuture ScheduledFuture} representing the task. * * <p>The specified {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} is used for this operation. * * @param delay/*from w w w . j a v a 2 s . c o m*/ * The delay after which this computation should be executed, negative to execute immediately * @param unit * The {@link java.util.concurrent.TimeUnit TimeUnit} to convert the specified {@code delay} * @param success * The success {@link java.util.function.Consumer Consumer} that should be called * once the {@link #queue(java.util.function.Consumer, java.util.function.Consumer)} operation completes successfully. * @param failure * The failure {@link java.util.function.Consumer Consumer} that should be called * in case of an error of the {@link #queue(java.util.function.Consumer, java.util.function.Consumer)} operation. * @param executor * The Non-null {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} that should be used * to schedule this operation * * @throws java.lang.IllegalArgumentException * If the provided TimeUnit or ScheduledExecutorService is {@code null} * * @return {@link java.util.concurrent.ScheduledFuture ScheduledFuture} * representing the delayed operation */ public ScheduledFuture<?> queueAfter(long delay, TimeUnit unit, Consumer<T> success, Consumer<Throwable> failure, ScheduledExecutorService executor) { Checks.notNull(executor, "Scheduler"); Checks.notNull(unit, "TimeUnit"); return executor.schedule(() -> queue(success, failure), delay, unit); }
From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java
@Test public void testTransactionAtomicity() throws Exception { // This test runs multiple transactions in parallel, with KeyValueService.put calls throwing // a RuntimeException from time to time and hanging other times. which effectively kills the // thread. We ensure that every transaction either adds 5 rows to the table or adds 0 rows // by checking at the end that the number of rows is a multiple of 5. final String tableName = "table"; Random random = new Random(1); final UnstableKeyValueService unstableKvs = new UnstableKeyValueService(keyValueService, random); final TestTransactionManager unstableTransactionManager = new TestTransactionManagerImpl(unstableKvs, timestampService, lockClient, lockService, transactionService, conflictDetectionManager, sweepStrategyManager);//from w w w .j av a 2 s. com ScheduledExecutorService service = PTExecutors.newScheduledThreadPool(20); for (int i = 0; i < 30; i++) { final int threadNumber = i; service.schedule(new Callable<Void>() { @Override public Void call() throws Exception { if (threadNumber == 10) { unstableKvs.setRandomlyThrow(true); } if (threadNumber == 20) { unstableKvs.setRandomlyHang(true); } Transaction transaction = unstableTransactionManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = transaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt nextIndex = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { byte[] dataBytes = row.getColumns().get("data".getBytes()); BigInteger dataValue = new BigInteger(dataBytes); nextIndex.setValue(Math.max(nextIndex.toInteger(), dataValue.intValue() + 1)); return true; } })); // nextIndex now contains the least row number not already in the table. Add 5 more // rows to the table. for (int j = 0; j < 5; j++) { int rowNumber = nextIndex.toInteger() + j; Cell cell = Cell.create(("row" + rowNumber).getBytes(), "data".getBytes()); transaction.put(tableName, ImmutableMap.of(cell, BigInteger.valueOf(rowNumber).toByteArray())); Thread.yield(); } transaction.commit(); return null; } }, i * 20, TimeUnit.MILLISECONDS); } service.shutdown(); service.awaitTermination(1, TimeUnit.SECONDS); // Verify each table has a number of rows that's a multiple of 5 Transaction verifyTransaction = txManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = verifyTransaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt numRows = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { numRows.increment(); return true; } })); Assert.assertEquals(0, numRows.toInteger() % 5); }
From source file:org.eclipse.smarthome.binding.mqtt.generic.internal.generic.ChannelState.java
/** * Subscribes to the state topic on the given connection and informs about updates on the given listener. * * @param connection A broker connection * @param scheduler A scheduler to realize the timeout * @param timeout A timeout in milliseconds. Can be 0 to disable the timeout and let the future return earlier. * @param channelStateUpdateListener An update listener * @return A future that completes with true if the subscribing worked, with false if the stateTopic is not set * and exceptionally otherwise.//from w ww . ja va2 s . com */ public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler, int timeout) { if (hasSubscribed) { return CompletableFuture.completedFuture(null); } this.connection = connection; if (StringUtils.isBlank(config.stateTopic)) { return CompletableFuture.completedFuture(null); } this.future = new CompletableFuture<>(); connection.subscribe(config.stateTopic, this).thenRun(() -> { hasSubscribed = true; if (timeout > 0 && !future.isDone()) { this.scheduledFuture = scheduler.schedule(this::receivedOrTimeout, timeout, TimeUnit.MILLISECONDS); } else { receivedOrTimeout(); } }).exceptionally(this::subscribeFail); return future; }
From source file:org.openbmp.db_rest.resources.Orr.java
/** * Get IGP RIB with merged BGP RIB for given RouterId * * Merged BGP RIB will contain duplicate entries for selected BGP paths based * on optimized next-hop selection and RR selection. For example: * * prefix 10.0.0.0/8 is equal in attributes but has two possible next-hops * 2.2.2.2 and 4.4.4.4, resulting tie breaker is IGP metric. * * Local routerId IGP has metric 20 to 2.2.2.2 and metric 31 to 4.4.4.4 * RR IGP has metric 10 to 4.4.4.4 and 31 to 2.2.2.2. * * Merged table would contain:/*from ww w . j a va2s . c o m*/ * 10.0.0.0/8 via 2.2.2.2 metric 20 (metric 31 on rr) marked as preferred (orr selected) * 10.0.0.0/8 via 4.4.4.4 metric 31 (metric 10 on rr) marked as not preferred (rr selected w/o orr) * * NOTE: The below method assumes (thus requires) that the bgp peer router * advertising the link-state data is the route-reflector. In other words, * peerHashId (bgp peer hash) learned from bmp router_hash_id is the * route-reflector. * * We can change this to allow selection of BGP peers (one or more bmp routers) * for the BGP RIB merge, but that requires more path/query params and is not needed right now. * * @param peerHashId Peer Hash ID of the BGP peer advertising link state information * @param protocol Either 'ospf' or 'isis' * @param routerId IPv4 or IPv6 print form router ID (use IPv4/IPv6 rid for ISIS) * @param where Advanced WHERE clause to filter the BGP merged prefixes */ @GET @Path("/peer/{peerHashId}/{protocol}/{routerId}") @Produces("application/json") public Response getLsOspfIGP(@PathParam("peerHashId") String peerHashId, @PathParam("protocol") String protocol, @PathParam("routerId") String routerId, @QueryParam("where") String where) { long startTime = System.currentTimeMillis(); ScheduledExecutorService thrPool = Executors.newScheduledThreadPool(2); queryThread thrs[] = new queryThread[2]; // Get IGP for requested router thrs[0] = new queryThread(this); thrs[0].setArgs(new String[] { peerHashId, routerId, protocol, "30" }); thrPool.schedule(thrs[0], 0, TimeUnit.MILLISECONDS); // Get the router's local router id // TODO: Change to support better identification of route reflector Map<String, List<DbColumnDef>> rrMap = getPeerRouterId(peerHashId); String rr_routerId = null; if (rrMap.size() > 0) rr_routerId = rrMap.entrySet().iterator().next().getValue().get(0).getValue(); if (rr_routerId == null) { System.out.println("Unable to get the routers routerID by peer hash " + peerHashId); return RestResponse.okWithBody("{}"); } // Get the RR IGP thrs[1] = new queryThread(this); thrs[1].setArgs(new String[] { peerHashId, rr_routerId, protocol, "120" }); thrPool.schedule(thrs[1], 0, TimeUnit.MILLISECONDS); // Wait for IGP query and store the results waitForThread(thrs[0]); Map<String, List<DbColumnDef>> igpMap = thrs[0].getResults(); if (igpMap.size() <= 0) { return RestResponse.okWithBody("{}"); } // Get the BGP RIB from RR router List<DbColumnDef> row = igpMap.entrySet().iterator().next().getValue(); String routerHashId = row.get(row.size() - 1).getValue(); String where_str = "router_hash_id = '" + routerHashId + "'"; if (where != null) where_str += " and " + where; StringBuilder query = new StringBuilder(); query.append("SELECT Prefix as prefix,PrefixLen as prefix_len,LocalPref,ASPath_Count,Origin,MED,NH\n"); query.append(" FROM v_routes WHERE "); query.append(where_str); query.append(" ORDER BY prefix_bin,PrefixLen LIMIT 1000\n"); Map<String, List<DbColumnDef>> bgpMap = DbUtils.select_DbToMap(mysql_ds, query.toString()); // Wait for RR IGP query and store the results waitForThread(thrs[1]); Map<String, List<DbColumnDef>> rr_igpMap = thrs[1].getResults(); //long queryTime = System.currentTimeMillis() - startTime; thrPool.shutdownNow(); /* * Merge BGP RIB into IGP */ Map<String, List<DbColumnDef>> mergeMap = new HashMap<String, List<DbColumnDef>>(); mergeMap.putAll(igpMap); mergeMap.putAll(mergeIgpWithBgp(igpMap, bgpMap, null, false)); mergeMap.putAll(mergeIgpWithBgp(rr_igpMap, bgpMap, igpMap, true)); long queryTime = System.currentTimeMillis() - startTime; return RestResponse.okWithBody(DbUtils.DbMapToJson("orr", mergeMap, queryTime)); }