Java Code Examples for java.util.concurrent.TimeoutException

The following are top voted examples for showing how to use java.util.concurrent.TimeoutException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ditb   File: HBaseAdmin.java   Source Code and License 7 votes vote down vote up
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");
    }
  });
}
 
Example 2
Project: java-threading   File: TestBase.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 3
Project: grpc-java-contrib   File: CompletableFutureEndToEndTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 4
Project: guava-mock   File: AbstractService.java   Source Code and License 6 votes vote down vote up
@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.");
  }
}
 
Example 5
Project: lams   File: BasicFuture.java   Source Code and License 6 votes vote down vote up
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();
                }
            }
        }
    }
}
 
Example 6
Project: gitplex-mit   File: PrioritizedExecutor.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 7
Project: mumu-rabbitmq   File: RabbitMQRPC.java   Source Code and License 5 votes vote down vote up
/**
 * 服务端开启服务
 */
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);
}
 
Example 8
Project: hygene   File: UITestBase.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 9
Project: jobson   File: JobManagerTest.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 10
Project: dropwizard-tinkerpop   File: TinkerPopManaged.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 11
Project: bench   File: ActorsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void actorCreation_is_set_when_actor_fails()
        throws ExecutionException, InterruptedException, TimeoutException {
    Actors.ActorHandle actorHandle = actors.create(actorConfig);

    verifyActorFailureThrowsFor(actorHandle.actorCreation());
}
 
Example 12
Project: iosched-reader   File: WaitableQueue.java   Source Code and License 5 votes vote down vote up
public void waitUntilEmpty(long timeoutMillis)
        throws TimeoutException, InterruptedException {
    add(mStopRequest);
    if (!mStopEvent.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException();
    }
}
 
Example 13
Project: kafka-0.11.0.0-src-with-comment   File: KafkaFutureImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 15
Project: tqdev-metrics   File: InstrumentedHandlerTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 16
Project: iTAP-controller   File: RemoteSyncFuture.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 17
Project: oreilly-reactive-architecture-old   File: CoffeeHouseApp.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 18
Project: incubator-netbeans   File: InterceptorTest.java   Source Code and License 5 votes vote down vote up
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");
    }
 
Example 19
Project: hadoop   File: DFSTestUtil.java   Source Code and License 5 votes vote down vote up
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);
  }
}
 
Example 20
Project: firebase-admin-java   File: OrderByTestIT.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 21
Project: rnrecord   File: AwaitablePromise.java   Source Code and License 5 votes vote down vote up
public T awaitResolve() {
    try {
        return resolveFuture.get(100, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new AwaitTimeoutException(e);
    }
}
 
Example 22
Project: mug   File: ParallelizerTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 23
Project: kafka-0.11.0.0-src-with-comment   File: ConsumerCoordinatorTest.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 24
Project: tascalate-concurrent   File: Timeouts.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: oreilly-reactive-with-akka   File: CoffeeHouseApp.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 26
Project: guava-mock   File: ServiceManager.java   Source Code and License 5 votes vote down vote up
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();
  }
}
 
Example 27
Project: oreilly-reactive-architecture-old   File: CoffeeHouseApp.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 28
Project: firebase-admin-java   File: QueryTestIT.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 29
Project: firebase-admin-java   File: QueryTestIT.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 30
Project: openjdk-jdk10   File: JSR166TestCase.java   Source Code and License 5 votes vote down vote up
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;
    }
}
 
Example 31
Project: GeekZone   File: RequestFuture.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: apache-tomcat-7.0.73-with-comment   File: AsyncChannelWrapperSecure.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 33
Project: guava-mock   File: FuturesTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 34
Project: GitHub   File: RequestFutureTarget.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: fuck_zookeeper   File: ClientRetry.java   Source Code and License 5 votes vote down vote up
@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();
    }
}
 
Example 36
Project: cyberduck   File: AbstractExceptionMappingService.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: hadoop   File: TestRbwSpaceReservation.java   Source Code and License 5 votes vote down vote up
/**
 * 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.
  }
}
 
Example 38
Project: mod-circulation-storage   File: StorageTestSuite.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 39
Project: incubator-netbeans   File: RepositoryUpdater.java   Source Code and License 5 votes vote down vote up
public void stop(@NullAllowed final Runnable postCleanTask) throws TimeoutException {
    synchronized (this) {
        if (state == State.STOPPED) {
            throw new IllegalStateException();
        }
        state = State.STOPPED;
        LOGGER.fine("Closing..."); //NOI18N

        PathRegistry.getDefault().removePathRegistryListener(this);
        rootsListeners.setListener(null, null);
        activeDocProvider.removeActiveDocumentListener(this);
        visibilitySupport.stop();
    }
    worker.cancelAll(postCleanTask);
}
 
Example 40
Project: BlockCanaryEx   File: ConnectServiceFuture.java   Source Code and License 5 votes vote down vote up
@Override
public ISamplerService get() throws InterruptedException, ExecutionException {
    try {
        return doGet(null);
    } catch (TimeoutException e) {
        throw new AssertionError(e);
    }
}
 
Example 41
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetAndThenListenForValueEvents()
    throws ExecutionException, TimeoutException, InterruptedException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  new WriteFuture(ref, "cabbage").timedGet();
  EventRecord event = new ReadFuture(ref).timedGet().get(0);

  assertEquals("cabbage", event.getSnapshot().getValue());
}
 
Example 42
Project: incubator-netbeans   File: BaseExecutionServiceTest.java   Source Code and License 5 votes vote down vote up
public void testCharset() throws InterruptedException, ExecutionException, TimeoutException {
    Charset charset = Charset.forName("UTF-16LE");
    final String[] lines = new String[] {"Process line \u1234", "Process line \u1235", "Process line \u1236"};

    TestInputStream is = new TestInputStream(TestInputUtils.prepareInputStream(lines, "\n", charset, true));
    TestProcess process = new TestProcess(0, is, null);
    is.setProcess(process);

    TestCallable callable = new TestCallable();
    callable.addProcess(process);

    final TestLineProcessor processor = new TestLineProcessor(false);
    BaseExecutionDescriptor descriptor = new BaseExecutionDescriptor().charset(charset).outProcessorFactory(
            new BaseExecutionDescriptor.InputProcessorFactory() {

        public InputProcessor newInputProcessor() {
            return InputProcessors.bridge(processor);
        }
    });

    BaseExecutionService service = BaseExecutionService.newService(
            callable, descriptor);

    Future<Integer> task = service.run();
    assertNotNull(task);

    assertEquals(0, task.get(PROCESS_TIMEOUT, TimeUnit.MILLISECONDS).intValue());
    assertTrue(process.isFinished());
    assertEquals(0, process.exitValue());

    List<String> processed = processor.getLinesProcessed();
    assertEquals(lines.length, processed.size());
    for (int i = 0; i < lines.length; i++) {
        assertEquals(lines[i], processed.get(i));
    }
}
 
Example 43
Project: fuck_zookeeper   File: FollowerResyncConcurrencyTest.java   Source Code and License 5 votes vote down vote up
private static DisconnectableZooKeeper createClient(int port,
        CountdownWatcher watcher)
    throws IOException, TimeoutException, InterruptedException
{
    DisconnectableZooKeeper zk = new DisconnectableZooKeeper(
            "127.0.0.1:" + port, ClientBase.CONNECTION_TIMEOUT, watcher);

    watcher.waitForConnected(CONNECTION_TIMEOUT);
    return zk;
}
 
Example 44
Project: oreilly-reactive-with-akka   File: CoffeeHouseApp.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 45
Project: bromium   File: ActionWithJSPreconditionBase.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(WebDriver driver, ReplayingState replayingState, EventSynchronizer eventSynchronizer) {
    String hashCodeToWaitFor = String.valueOf(getJSEventToWaitFor().hashCode());
    logger.info("Condition {} has hashcode {}", getJSEventToWaitFor(), hashCodeToWaitFor);
    SynchronizationEvent synchronizationEvent = new JSPrecondition(hashCodeToWaitFor, eventSynchronizer, replayingState);
    try {
        eventSynchronizer.awaitUntil(synchronizationEvent);
    } catch (InterruptedException | TimeoutException e) {
        throw new WebDriverActionExecutionException("Exception while awaiting JS precondition", e, new InstanceBasedAutomationResultBuilder());
    }

    executeAfterJSPreconditionHasBeenSatisfied(driver, replayingState);
}
 
Example 46
Project: jdk8u-jdk   File: CompletableFuture.java   Source Code and License 5 votes vote down vote up
/**
 * Returns raw result after waiting, or null if interrupted, or
 * throws TimeoutException on timeout.
 */
private Object timedGet(long nanos) throws TimeoutException {
    if (Thread.interrupted())
        return null;
    if (nanos <= 0L)
        throw new TimeoutException();
    long d = System.nanoTime() + nanos;
    Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
    boolean queued = false;
    Object r;
    // We intentionally don't spin here (as waitingGet does) because
    // the call to nanoTime() above acts much like a spin.
    while ((r = result) == null) {
        if (!queued)
            queued = tryPushStack(q);
        else if (q.interruptControl < 0 || q.nanos <= 0L) {
            q.thread = null;
            cleanStack();
            if (q.interruptControl < 0)
                return null;
            throw new TimeoutException();
        }
        else if (q.thread != null && result == null) {
            try {
                ForkJoinPool.managedBlock(q);
            } catch (InterruptedException ie) {
                q.interruptControl = -1;
            }
        }
    }
    if (q.interruptControl < 0)
        r = null;
    q.thread = null;
    postComplete();
    return r;
}
 
Example 47
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testLargeNumericPriorities()
    throws TestFailure, TimeoutException, InterruptedException, ExecutionException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference ref1 = refs.get(0);
  DatabaseReference ref2 = refs.get(1);

  double priority = 1356721306842.0;

  new WriteFuture(ref1, 5, priority).timedGet();
  DataSnapshot snap = new ReadFuture(ref2).timedGet().get(0).getSnapshot();
  assertEquals(priority, snap.getPriority());
}
 
Example 48
Project: j1st-mqtt   File: RabbitMQApplicationCommunicator.java   Source Code and License 5 votes vote down vote up
@Override
public void init(AbstractConfiguration config, ApplicationListenerFactory factory) {
    try {
        ConnectionFactory cf = new ConnectionFactory();
        cf.setUsername(config.getString("rabbitmq.userName", ConnectionFactory.DEFAULT_USER));
        cf.setPassword(config.getString("rabbitmq.password", ConnectionFactory.DEFAULT_PASS));
        cf.setVirtualHost(config.getString("rabbitmq.virtualHost", ConnectionFactory.DEFAULT_VHOST));
        cf.setAutomaticRecoveryEnabled(true);
        cf.setExceptionHandler(new RabbitMQExceptionHandler());
        this.conn = cf.newConnection(Address.parseAddresses(config.getString("rabbitmq.addresses")));
        this.channel = conn.createChannel();

        logger.trace("Initializing RabbitMQ application resources ...");

        APPLICATION_TOPIC = config.getString("communicator.application.topic");
        this.channel.exchangeDeclare(APPLICATION_TOPIC, "topic", true);

        logger.trace("Initializing RabbitMQ application consumer's workers ...");

        Channel consumerChan = this.conn.createChannel();
        consumerChan.queueDeclare(config.getString("rabbitmq.app.queueName"), true, false, true, null);
        consumerChan.queueBind(config.getString("rabbitmq.app.queueName"), APPLICATION_TOPIC, config.getString("rabbitmq.app.routingKey"));
        consumerChan.basicConsume(config.getString("rabbitmq.app.queueName"), true, new RabbitMQApplicationConsumer(consumerChan, factory.newListener()));

    } catch (IOException | TimeoutException e) {
        logger.error("Failed to connect to RabbitMQ servers", e);
        throw new IllegalStateException("Init RabbitMQ communicator failed");
    }
}
 
Example 49
Project: AvenueNet   File: ErrorHandle.java   Source Code and License 5 votes vote down vote up
@Override
public ApiException onHandle(Throwable t) {
    final Context context = AvenueNet.getConfig(ConfigKey.APP_CONTEXT);

    final ApiException exception;
    if (t instanceof ApiException) {
        exception = (ApiException) t;
    } else if (t instanceof TimeoutException) {
        exception = new ApiException(10001, "网络连接超时");
    } else if (t instanceof SocketTimeoutException) {
        exception = new ApiException(10001, "网络连接超时");
    } else {
        exception = new ApiException(-1, "未知错误");
    }
    Toast.makeText(context, exception.getMessage(), Toast.LENGTH_SHORT).show();
    return exception;
}
 
Example 50
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void invalidDoubleValues()
    throws DatabaseException, TestFailure, TimeoutException, InterruptedException {
  DatabaseReference node = IntegrationTestUtils.getRandomNode(masterApp);
  Object[] invalidValues =
      new Object[] {
          Double.NEGATIVE_INFINITY,
          Double.POSITIVE_INFINITY,
          Double.NaN,
          Float.NEGATIVE_INFINITY,
          Float.POSITIVE_INFINITY,
          Float.NaN
      };
  for (Object invalidValue : invalidValues) {
    try {
      node.setValueAsync(invalidValue);
      fail("NaN or Inf are not allowed as values.");
    } catch (DatabaseException expected) {
      assertEquals("Invalid value: Value cannot be NaN, Inf or -Inf.", expected.getMessage());
    }
  }
}
 
Example 51
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testNamespaceCaseInsensitive()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {

  String child = "" + new Random().nextInt(100000000);
  DatabaseReference ref1 = FirebaseDatabase.getInstance(masterApp).getReference(child);

  String url = "https://" + IntegrationTestUtils.getProjectId().toUpperCase() + ".firebaseio.com/"
      + child;
  DatabaseReference ref2 = FirebaseDatabase.getInstance(masterApp).getReferenceFromUrl(url);

  new WriteFuture(ref1, "testdata").timedGet();
  DataSnapshot snap = TestHelpers.getSnap(ref2);
  assertEquals("testdata", snap.getValue());
}
 
Example 52
Project: yacy_grid_mcp   File: RabbitQueueFactory.java   Source Code and License 5 votes vote down vote up
private void init() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setHost(this.server);
    if (this.port > 0) factory.setPort(this.port);
    if (this.username != null && this.username.length() > 0) factory.setUsername(this.username);
    if (this.password != null && this.password.length() > 0) factory.setPassword(this.password);
    try {
        this.connection = factory.newConnection();
        //Map<String, Object> map = this.connection.getServerProperties();
        if (!this.connection.isOpen()) throw new IOException("no connection");
        this.channel = connection.createChannel();
        if (!this.channel.isOpen()) throw new IOException("no channel");
        this.queues = new ConcurrentHashMap<>();
    } catch (TimeoutException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 53
Project: GitHub   File: CachingTest.java   Source Code and License 5 votes vote down vote up
@Test
public void submit_withPreviousButNoLongerReferencedIdenticalRequest_completesFromMemoryCache()
    throws InterruptedException, TimeoutException, ExecutionException {
  // We can't allow any mocks (RequestListner, Target etc) to reference this request or the test
  // will fail due to the transient strong reference to the request.
  concurrency.get(
      GlideApp.with(context)
          .load(ResourceIds.raw.canonical)
          .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
          .submit(IMAGE_SIZE_PIXELS, IMAGE_SIZE_PIXELS));

  // Force the collection of weak references now that the listener/request in the first load is no
  // longer referenced.
  Runtime.getRuntime().gc();
  concurrency.pokeMainThread();

  concurrency.get(
      GlideApp.with(context)
          .load(ResourceIds.raw.canonical)
          .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
          .listener(requestListener)
          .submit(IMAGE_SIZE_PIXELS, IMAGE_SIZE_PIXELS));

  verify(requestListener)
      .onResourceReady(
          anyDrawable(),
          any(),
          anyTarget(),
          eq(DataSource.MEMORY_CACHE),
          anyBoolean());
}
 
Example 54
Project: firebase-admin-java   File: DataTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testUpdateRaisesCorrectLocalEvents()
    throws InterruptedException, TestFailure, TimeoutException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final ReadFuture readFuture = ReadFuture.untilCountAfterNull(ref, 2);

  ref.setValueAsync(new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4).build());

  EventHelper helper = new EventHelper().addValueExpectation(ref.child("a"))
      .addValueExpectation(ref.child("d"))
      .addChildExpectation(ref, Event.EventType.CHILD_CHANGED, "a")
      .addChildExpectation(ref, Event.EventType.CHILD_CHANGED, "d").addValueExpectation(ref)
      .startListening(true);

  ref.updateChildrenAsync(new MapBuilder().put("a", 4).put("d", 1).build());
  helper.waitForEvents();
  List<EventRecord> events = readFuture.timedGet();
  helper.cleanup();

  Map<String, Object> expected = new MapBuilder().put("a", 4L).put("b", 2L).put("c", 3L)
      .put("d", 1L).build();
  Object result = events.get(events.size() - 1).getSnapshot().getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 55
Project: chaosflix   File: MediaApiServiceTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException, TimeoutException {
	server = new MockWebServer();
	server.start();
	serverUrl = server.url("").toString();

	Intent s = new Intent(InstrumentationRegistry.getTargetContext(),
			MediaApiService.class);
	s.putExtra(MediaApiService.RECORDING_URL,serverUrl);
	s.putExtra(MediaApiService.STREAMING_URL,serverUrl);
	IBinder binder = mServiceRule.bindService(s);
	service = ((MediaApiService.LocalBinder) binder).getService();
}
 
Example 56
Project: guava-mock   File: UninterruptibleFutureTest.java   Source Code and License 5 votes vote down vote up
public void testMakeUninterruptible_timedGetZeroTimeoutAttempted()
    throws TimeoutException, ExecutionException {
  SettableFuture<String> future = SettableFuture.create();
  future.set(RESULT);
  /*
   * getUninterruptibly should call the timed get method once with a
   * wait of 0 seconds (and it should succeed, since the result is already
   * available).
   */
  assertEquals(RESULT, getUninterruptibly(future, 0, SECONDS));
}
 
Example 57
Project: easyhbase   File: MonitoredExecutorService.java   Source Code and License 5 votes vote down vote up
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> callables, long timeout, TimeUnit
        unit) throws ExecutionException, InterruptedException, TimeoutException {
    submitted.mark(callables.size());
    Collection<? extends Callable<T>> instrumented = instrument(callables);
    try {
        return delegate.invokeAny(instrumented, timeout, unit);
    } catch (RejectedExecutionException ree) {
        rejected.mark(callables.size());
        throw ree;
    }
}
 
Example 58
Project: kafka-0.11.0.0-src-with-comment   File: DistributedHerder.java   Source Code and License 5 votes vote down vote up
/**
 * Try to read to the end of the config log within the given timeout
 * @param timeoutMs maximum time to wait to sync to the end of the log
 * @return true if successful, false if timed out
 */
private boolean readConfigToEnd(long timeoutMs) {
    log.info("Current config state offset {} is behind group assignment {}, reading to end of config log", configState.offset(), assignment.offset());
    try {
        configBackingStore.refresh(timeoutMs, TimeUnit.MILLISECONDS);
        configState = configBackingStore.snapshot();
        log.info("Finished reading to end of log and updated config snapshot, new config log offset: {}", configState.offset());
        return true;
    } catch (TimeoutException e) {
        // in case reading the log takes too long, leave the group to ensure a quick rebalance (although by default we should be out of the group already)
        // and back off to avoid a tight loop of rejoin-attempt-to-catch-up-leave
        log.warn("Didn't reach end of config log quickly enough", e);
        member.maybeLeaveGroup();
        backoff(workerUnsyncBackoffMs);
        return false;
    }
}
 
Example 59
Project: openjdk-systemtest   File: RunFuture.java   Source Code and License 5 votes vote down vote up
public static void get(Future<?> task) throws ExecutionException, InterruptedException, TimeoutException {
	if (block) {
		while(!task.isDone()) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// do nothing
			}
		}
		task.get();
	} else {
		task.get(GET_TIMEOUT_SECONDS, TimeUnit.SECONDS);
	}
}
 
Example 60
Project: https-github.com-apache-zookeeper   File: ClientBase.java   Source Code and License 5 votes vote down vote up
synchronized public void waitForSyncConnected(long timeout)
        throws InterruptedException, TimeoutException
{
    long expire = Time.currentElapsedTime() + timeout;
    long left = timeout;
    while(!syncConnected && left > 0) {
        wait(left);
        left = expire - Time.currentElapsedTime();
    }
    if (!syncConnected) {
        throw new TimeoutException("Failed to connect to read-write ZooKeeper server.");
    }
}