private void waitTableEnabled(final long deadlineTs) throws IOException, TimeoutException { waitForState(deadlineTs, new WaitForStateCallable() { @Override public boolean checkState(int tries) throws IOException { boolean enabled; try { enabled = getAdmin().isTableEnabled(tableName); } catch (TableNotFoundException tnfe) { return false; } return enabled && getAdmin().isTableAvailable(tableName); } @Override public void throwInterruptedException() throws InterruptedIOException { throw new InterruptedIOException("Interrupted when waiting for table to be enabled"); } @Override public void throwTimeoutException(long elapsedTime) throws TimeoutException { throw new TimeoutException("Table " + tableName + " not yet enabled after " + elapsedTime + "msec"); } }); }
/** * Verifies that continuations scheduled on a future will not be executed inline with the specified completing * action. * * @param antecedent The future to test. * @param completingAction The action that results in the synchronous completion of the future. */ protected static void verifyDoesNotInlineContinuations(@NotNull CompletableFuture<?> antecedent, @NotNull Runnable completingAction) { Requires.notNull(antecedent, "antecedent"); Requires.notNull(completingAction, "completingAction"); CompletableFuture<Void> completingActionFinished = new CompletableFuture<>(); CompletableFuture<Void> continuation = antecedent.handle((result, exception) -> { try { return completingActionFinished.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException ex) { throw new CompletionException(ex); } }); completingAction.run(); completingActionFinished.complete(null); // Rethrow the exception if it turned out it deadlocked. continuation.join(); }
@Override public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException { if (monitor.enterWhenUninterruptibly(hasReachedRunning, timeout, unit)) { try { checkCurrentState(RUNNING); } finally { monitor.leave(); } } else { // It is possible due to races the we are currently in the expected state even though we // timed out. e.g. if we weren't event able to grab the lock within the timeout we would never // even check the guard. I don't think we care too much about this use case but it could lead // to a confusing error message. throw new TimeoutException("Timed out waiting for " + this + " to reach the RUNNING state."); } }
public synchronized T get(long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long msecs = unit.toMillis(timeout); long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis(); long waitTime = msecs; if (this.completed) { return getResult(); } else if (waitTime <= 0) { throw new TimeoutException(); } else { for (;;) { wait(waitTime); if (this.completed) { return getResult(); } else { waitTime = msecs - (System.currentTimeMillis() - startTime); if (waitTime <= 0) { throw new TimeoutException(); } } } } }
@Test public void testStartAtWithTwoArguments() throws TestFailure, ExecutionException, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); new WriteFuture(ref, MapBuilder.of( "Walker", MapBuilder.of("name", "Walker", "score", 20, ".priority", 20), "Michael", MapBuilder.of("name", "Michael", "score", 100, ".priority", 100))) .timedGet(); DataSnapshot snap = TestHelpers.getSnap(ref.startAt(20, "Walker").limitToFirst(2)); List<String> expected = ImmutableList.of("Walker", "Michael"); int i = 0; for (DataSnapshot child : snap.getChildren()) { assertEquals(expected.get(i), child.getKey()); i++; } assertEquals(2, i); }
private synchronized T doGet(Long timeoutMs) throws InterruptedException, ExecutionException, TimeoutException { if (mException != null) { throw new ExecutionException(mException); } if (mResultReceived) { return mResult; } if (timeoutMs == null) { wait(0); } else if (timeoutMs > 0) { wait(timeoutMs); } if (mException != null) { throw new ExecutionException(mException); } if (!mResultReceived) { throw new TimeoutException(); } return mResult; }
/** * Call the non-timed {@link Future#get()} in a way that allows us to abort if it's expected to * hang forever. More precisely, if it's expected to return, we simply call it[*], but if it's * expected to hang (because one of the input futures that we know makes it up isn't done yet), * then we call it in a separate thread (using pseudoTimedGet). The result is that we wait as long * as necessary when the method is expected to return (at the cost of hanging forever if there is * a bug in the class under test) but that we time out fairly promptly when the method is expected * to hang (possibly too quickly, but too-quick failures should be very unlikely, given that we * used to bail after 20ms during the expected-successful tests, and there we saw a failure rate * of ~1/5000, meaning that the other thread's get() call nearly always completes within 20ms if * it's going to complete at all). * * [*] To avoid hangs, I've disabled the in-thread calls. This makes the test take (very roughly) * 2.5s longer. (2.5s is also the maximum length of time we will wait for a timed get that is * expected to succeed; the fact that the numbers match is only a coincidence.) See the comment * below for how to restore the fast but hang-y version. */ @GwtIncompatible // used only in GwtIncompatible tests private static List<String> conditionalPseudoTimedGetUninterruptibly( TestFutureBatch inputs, ListenableFuture<String> iFuture, ListenableFuture<String> jFuture, ListenableFuture<List<String>> future, int timeout, TimeUnit unit) throws ExecutionException, TimeoutException { /* * For faster tests (that may hang indefinitely if the class under test has * a bug!), switch the second branch to call untimed future.get() instead of * pseudoTimedGet. */ return (inputs.hasDelayed(iFuture, jFuture)) ? pseudoTimedGetUninterruptibly(future, timeout, unit) : pseudoTimedGetUninterruptibly(future, 2500, MILLISECONDS); }
public void disconnect() { if (client != null) { log.info("Disconnecting from OPC-UA server!"); try { client.disconnect().get(10, TimeUnit.SECONDS); log.info("Disconnected from OPC-UA server!"); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.info("Failed to disconnect from OPC-UA server!"); } } }
private static void writeRequest(AsyncChannelWrapper channel, ByteBuffer request, long timeout) throws TimeoutException, InterruptedException, ExecutionException { int toWrite = request.limit(); Future<Integer> fWrite = channel.write(request); Integer thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS); toWrite -= thisWrite.intValue(); while (toWrite > 0) { fWrite = channel.write(request); thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS); toWrite -= thisWrite.intValue(); } }
/** * 服务端开启服务 */ public void service() throws IOException, TimeoutException { RabbitMQChannel channel = new RabbitMQChannel().channel(); channel.getChannel().queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.getChannel().basicQos(1); System.out.println("等待rpc客户端连接..."); Consumer consumer = new DefaultConsumer(channel.getChannel()) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { AMQP.BasicProperties replyProps = new AMQP.BasicProperties .Builder() .correlationId(properties.getCorrelationId()) .build(); String response = ""; try { String message = new String(body, "UTF-8"); System.out.println("服务端接受到消息:" + message); response = message + UUID.randomUUID().toString(); } catch (RuntimeException e) { e.printStackTrace(); } finally { channel.getChannel().basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.getChannel().basicAck(envelope.getDeliveryTag(), false); System.out.println("服务端将处理结果:" + response + ",返回客户单\n"); } } }; channel.getChannel().basicConsume(RPC_QUEUE_NAME, false, consumer); }
/** * Set up application before each test. * Afterwards, calls the {@link #beforeEach()} method. * * @throws TimeoutException if unable to set up application * @throws UIInitialisationException if ui was not properly initialized * @see FxToolkit#setupApplication(Class, String...) */ @BeforeEach public final void basicBeforeEach() throws TimeoutException, UIInitialisationException { this.primaryStage = FxToolkit.registerPrimaryStage(); this.application = (Hygene) FxToolkit.setupApplication(Hygene.class); this.context = Hygene.getInstance().getContext(); FxToolkit.showStage(); beforeEach(); }
@Test public void testSubmitPromiseResolvesWhenExecutorPromiseResolves2() throws InterruptedException, ExecutionException, TimeoutException { final CancelablePromise<JobExecutionResult> p = new SimpleCancelablePromise<>(); final JobExecutor jobExecutor = MockJobExecutor.thatUses(p); final JobManager jobManager = createManagerWith(jobExecutor); final CancelablePromise<FinalizedJob> ret = jobManager.submit(STANDARD_VALID_REQUEST).getRight(); p.complete(JobExecutionResult.fromExitCode(0)); assertThat(ret.get(DEFAULT_TIMEOUT, MILLISECONDS)).isNotNull(); }
@Override public void stop() throws Exception { LOG.info("Attempting to shutdown TinkerPop cluster connection."); CompletableFuture<Void> future = cluster.closeAsync(); try { future.get(shutdownTimeout.toMilliseconds(), TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { LOG.warn("Unable to close TinkerPop cluster after {}", shutdownTimeout); } }
@Test public void actorCreation_is_set_when_actor_fails() throws ExecutionException, InterruptedException, TimeoutException { Actors.ActorHandle actorHandle = actors.create(actorConfig); verifyActorFailureThrowsFor(actorHandle.actorCreation()); }
public void waitUntilEmpty(long timeoutMillis) throws TimeoutException, InterruptedException { add(mStopRequest); if (!mStopEvent.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) { throw new TimeoutException(); } }
/** * Waits if necessary for at most the given time for this future to complete, and then returns * its result, if available. */ @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { SingleWaiter<T> waiter = new SingleWaiter<T>(); addWaiter(waiter); return waiter.await(timeout, unit); }
@Test public void testNegativeIntegerKeys() throws TestFailure, ExecutionException, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); new WriteFuture(ref, new MapBuilder().put("-1", "minus-one").put("0", "zero").put("1", "one").build()) .timedGet(); DataSnapshot snap = TestHelpers.getSnap(ref); Map<String, Object> expected = new MapBuilder().put("-1", "minus-one").put("0", "zero") .put("1", "one").build(); Object result = snap.getValue(); TestHelpers.assertDeepEquals(expected, result); }
@Test public void serverRunsAndRespondsCorrectly() throws ExecutionException, IOException, InterruptedException, TimeoutException { final String name = UUID.randomUUID().toString(); Server server = ServerBuilder.forPort(9999) .addService(new GreeterImpl()) .build(); server.start(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()) .usePlaintext(true) .build(); GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel); CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build()); await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name)); channel.shutdown(); channel.awaitTermination(1, TimeUnit.MINUTES); channel.shutdownNow(); server.shutdown(); server.awaitTermination(1, TimeUnit.MINUTES); server.shutdownNow(); }
@Test public void shouldMeasureHello() throws InterruptedException, ExecutionException, TimeoutException { ContentResponse response = client.GET(url + "/hello"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentAsString()).isEqualTo("Hello World!"); assertThat(registry.get("jetty.Response.Invocations", "2xx-responses")).isEqualTo(1L); assertThat(registry.get("jetty.Response.Durations", "2xx-responses")).isEqualTo(123456789L); }
@Override public SyncReply get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (reply != null) return reply; synchronized (notify) { notify.wait(TimeUnit.MILLISECONDS.convert(timeout, unit)); } if (reply == null) throw new TimeoutException(); return reply; }
private void run() throws IOException, TimeoutException, InterruptedException { log.warning( String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"), getClass().getSimpleName() ); commandLoop(); Await.ready(system.whenTerminated(), Duration.Inf()); }
public void testLockTimeout() throws IOException, InterruptedException, TimeoutException { File f = new File(getWorkDir(), "file"); f.createNewFile(); write(f, "1"); long ts = f.lastModified(); // change file and block the storing for some time right after the msg gets intercepted FileObject fo = FileUtil.toFileObject(f); long BLOCK_TIME = 15000; long LOCK_TIME = 3; System.setProperty("netbeans.t9y.localhistory.release-lock.timeout", "" + LOCK_TIME); LogHandler fileStoreBlock = new LogHandler("finnished copy file " + getPath(f), LogHandler.Compare.STARTS_WITH); fileStoreBlock.block(BLOCK_TIME); LogHandler beforeDeleteBlock = new LogHandler("beforeDelete for file " + getPath(f) + " was blocked", LogHandler.Compare.STARTS_WITH); long t = System.currentTimeMillis(); fo.delete(); assertTrue(beforeDeleteBlock.isDone()); // beforeDelete is done long d = System.currentTimeMillis() - t; if(d < LOCK_TIME * 1000) { fail("should have been locked for at least " + LOCK_TIME + " seconds but was " + d); } else if(System.currentTimeMillis() - t >= BLOCK_TIME) { fail("was blocked longer that expected: " + (BLOCK_TIME / 1000) + " seconds"); } // great, the lock was released, now lets wait until // is realy stored fileStoreBlock.waitUntilDone(); StoreEntry entry = LocalHistory.getInstance().getLocalHistoryStore().getStoreEntry(VCSFileProxy.createFileProxy(f), ts); assertNotNull(entry); assertEntry(entry, "1"); }
public void waitReplication(FileSystem fs, String topdir, short value) throws IOException, InterruptedException, TimeoutException { Path root = new Path(topdir); /** wait for the replication factor to settle down */ for (int idx = 0; idx < nFiles; idx++) { waitReplication(fs, new Path(root, files[idx].getName()), value); } }
@Test public void testRemovingDefaultListener() throws InterruptedException, ExecutionException, TimeoutException, TestFailure, IOException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; Object initialData = MapBuilder.of("key", "value"); new WriteFuture(ref, initialData).timedGet(); ValueEventListener listener = ref.orderByKey() .addValueEventListener( new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) {} @Override public void onCancelled(DatabaseError error) {} }); ref.addValueEventListener(listener); // Should remove both listener and should remove the listen sent to the server ref.removeEventListener(listener); // This used to crash because a listener for ref.orderByKey() existed already Object result = new ReadFuture(ref.orderByKey()).waitForLastValue(); assertEquals(initialData, result); }
public T awaitResolve() { try { return resolveFuture.get(100, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new AwaitTimeoutException(e); } }
@Test public void testAwaitTimeoutCancelsInFlightTasks() throws InterruptedException { assumeFalse(threading == Threading.DIRECT); assumeTrue(mode == Mode.INTERRUPTIBLY); maxInFlight = 2; timeout = Duration.ofMillis(1); assertThrows( TimeoutException.class, () -> parallelize(serialTasks( () -> blockFor(1), // Will be interrupted () -> blockFor(2)))); // Might be interrupted shutdownAndAssertInterruptedKeys().contains(1); }
private void closeVerifyTimeout(final ConsumerCoordinator coordinator, final long closeTimeoutMs, final long requestTimeoutMs, long expectedMinTimeMs, long expectedMaxTimeMs) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); try { boolean coordinatorUnknown = coordinator.coordinatorUnknown(); // Run close on a different thread. Coordinator is locked by this thread, so it is // not safe to use the coordinator from the main thread until the task completes. Future<?> future = executor.submit(new Runnable() { @Override public void run() { coordinator.close(Math.min(closeTimeoutMs, requestTimeoutMs)); } }); // Wait for close to start. If coordinator is known, wait for close to queue // at least one request. Otherwise, sleep for a short time. if (!coordinatorUnknown) client.waitForRequests(1, 1000); else Thread.sleep(200); if (expectedMinTimeMs > 0) { time.sleep(expectedMinTimeMs - 1); try { future.get(500, TimeUnit.MILLISECONDS); fail("Close completed ungracefully without waiting for timeout"); } catch (TimeoutException e) { // Expected timeout } } if (expectedMaxTimeMs >= 0) time.sleep(expectedMaxTimeMs - expectedMinTimeMs + 2); future.get(2000, TimeUnit.MILLISECONDS); } finally { executor.shutdownNow(); } }
/** * Creates a promise that is resolved erronously with {@link TimeoutException} after delay specified * @param duration * the duration of timeout * @return * the new promise */ static <T> Promise<T> failAfter(Duration duration) { final CompletablePromise<T> promise = new CompletablePromise<>(); final Future<?> timeout = scheduler.schedule( () -> promise.onFailure(new TimeoutException("Timeout after " + duration)), duration.toMillis(), TimeUnit.MILLISECONDS ); promise.whenComplete((r, e) -> timeout.cancel(true)); return promise; }
void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException { monitor.enter(); try { if (!monitor.waitForUninterruptibly(stoppedGuard, timeout, unit)) { throw new TimeoutException( "Timeout waiting for the services to stop. The following " + "services have not stopped: " + Multimaps.filterKeys(servicesByState, not(in(EnumSet.of(TERMINATED, FAILED))))); } } finally { monitor.leave(); } }
@Test public void testLimitOnUnsyncedNode() throws TestFailure, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); // This will timeout if value never fires assertEquals(1, new ReadFuture(ref.limitToLast(1)).timedGet().size()); }
@Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { for (Callable<T> task: tasks) Preconditions.checkArgument(task instanceof PriorityAware); return super.invokeAny(tasks, timeout, unit); }
public int await() { try { return super.await(2 * LONG_DELAY_MS, MILLISECONDS); } catch (TimeoutException timedOut) { throw new AssertionFailedError("timed out"); } catch (Exception fail) { AssertionFailedError afe = new AssertionFailedError("Unexpected exception: " + fail); afe.initCause(fail); throw afe; } }
@Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { boolean latchResult = completionLatch.await(timeout, unit); if (latchResult == false) { throw new TimeoutException(); } if (throwable != null) { throw new ExecutionException(throwable); } return result; }
private synchronized R doGet(Long timeoutMillis) throws ExecutionException, InterruptedException, TimeoutException { if (assertBackgroundThread && !isDone()) { Util.assertBackgroundThread(); } if (isCancelled) { throw new CancellationException(); } else if (loadFailed) { throw new ExecutionException(new IllegalStateException("Load failed")); } else if (resultReceived) { return resource; } if (timeoutMillis == null) { waiter.waitForTimeout(this, 0); } else if (timeoutMillis > 0) { waiter.waitForTimeout(this, timeoutMillis); } if (Thread.interrupted()) { throw new InterruptedException(); } else if (loadFailed) { throw new ExecutionException(new IllegalStateException("Load failed")); } else if (isCancelled) { throw new CancellationException(); } else if (!resultReceived) { throw new TimeoutException(); } return resource; }
@Test public void testClientRetry() throws IOException, InterruptedException, TimeoutException{ CountdownWatcher cdw1 = new CountdownWatcher(); CountdownWatcher cdw2 = new CountdownWatcher(); ZooKeeper zk = new ZooKeeper(hostPort, 10000, cdw1); try { cdw1.waitForConnected(CONNECTION_TIMEOUT); ZooKeeper zk2 = new ZooKeeper(hostPort, 10000, cdw2); try { States s1 = zk.getState(); States s2 = zk2.getState(); Assert.assertSame(s1,States.CONNECTED); Assert.assertSame(s2,States.CONNECTING); cdw1.reset(); cdw1.waitForDisconnected(CONNECTION_TIMEOUT); cdw2.waitForConnected(CONNECTION_TIMEOUT); Assert.assertSame(zk2.getState(),States.CONNECTED); } finally { zk2.close(); } } finally { zk.close(); } }
protected BackgroundException wrap(final T failure, final String title, final StringBuilder buffer) { if(buffer.toString().isEmpty()) { log.warn(String.format("No message for failure %s", failure)); this.append(buffer, LocaleFactory.localizedString("Interoperability failure", "Error")); } for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof InterruptedIOException) { // Handling socket timeouts return new ConnectionTimeoutException(buffer.toString(), failure); } if(cause instanceof TimeoutException) { // return new ConnectionTimeoutException(buffer.toString(), failure); } if(cause instanceof SocketException) { return new DefaultSocketExceptionMappingService().map((SocketException) cause); } if(cause instanceof EOFException) { return new ConnectionRefusedException(buffer.toString(), failure); } if(cause instanceof UnknownHostException) { return new ResolveFailedException(buffer.toString(), failure); } if(cause instanceof NoHttpResponseException) { return new ConnectionRefusedException(buffer.toString(), failure); } } return new BackgroundException(title, buffer.toString(), failure); }
/** * Ensure that reserved space is released when the client goes away * unexpectedly. * * The verification is done for each replica in the write pipeline. * * @throws IOException */ @Test(timeout=300000) public void testSpaceReleasedOnUnexpectedEof() throws IOException, InterruptedException, TimeoutException { final short replication = 3; startCluster(BLOCK_SIZE, replication, -1); final String methodName = GenericTestUtils.getMethodName(); final Path file = new Path("/" + methodName + ".01.dat"); // Write 1 byte to the file and kill the writer. FSDataOutputStream os = fs.create(file, replication); os.write(new byte[1]); os.hsync(); DFSTestUtil.abortStream((DFSOutputStream) os.getWrappedStream()); // Ensure all space reserved for the replica was released on each // DataNode. for (DataNode dn : cluster.getDataNodes()) { final FsVolumeImpl volume = (FsVolumeImpl) dn.getFSDataset().getVolumes().get(0); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return (volume.getReservedForRbw() == 0); } }, 500, Integer.MAX_VALUE); // Wait until the test times out. } }
private static void startVerticle(DeploymentOptions options) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture deploymentComplete = new CompletableFuture<String>(); vertx.deployVerticle(RestVerticle.class.getName(), options, res -> { if(res.succeeded()) { deploymentComplete.complete(res.result()); } else { deploymentComplete.completeExceptionally(res.cause()); } }); deploymentComplete.get(20, TimeUnit.SECONDS); }