@Override protected void sleepMicrosUninterruptibly(long micros) { if (micros > 0) { Uninterruptibles.sleepUninterruptibly(micros, MICROSECONDS); } } };
@Override public void runUninterruptiblyWithTimeout( Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException { checkNotNull(runnable); checkNotNull(timeoutUnit); checkPositiveTimeout(timeoutDuration); Future<?> future = executor.submit(runnable); try { Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); } catch (TimeoutException e) { future.cancel(true /* mayInterruptIfRunning */); throw e; } catch (ExecutionException e) { wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause()); throw new AssertionError(); } }
@Override public void failure(Service service) { failEnter.countDown(); // block until after the service manager is shutdown Uninterruptibles.awaitUninterruptibly(failLeave); } });
@Test(groups = "long") public void sessions_should_not_leak_connections() { assertEquals(stressCluster.manager.sessions.size(), 0); assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); assertEquals(stressCluster.manager.sessions.size(), 1); int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster); assertEquals( CountDownLatch startSignal = new CountDownLatch(2); List<ListenableFuture<Session>> openSessionFutures = openSessionsConcurrently(halfOfTheSessions, startSignal); List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions, startSignal); startSignal.countDown(); waitFor(openSessionFutures); waitFor(closeSessionsFutures); Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS); Uninterruptibles.sleepUninterruptibly(60, TimeUnit.SECONDS);
private void enterSatisfyGuardAndLeaveInAnotherThread() { final CountDownLatch startedLatch = new CountDownLatch(1); startThread( new Runnable() { @Override public void run() { startedLatch.countDown(); enterSatisfyGuardAndLeaveInCurrentThread(); } }); awaitUninterruptibly(startedLatch); }
@Test public void testSupplierExpirationReloadsTheCache() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); // Load an image into the cache assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); // Once the supplier expires, reloading it will load the initial values // (it is a hardcoded supplier), so the just loaded image should be gone Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS); assertEquals(imageCache.get().size(), 1); assertFalse(any(imageCache.get(), idEquals("foo"))); } }
@Test(groups = "long") @CCMConfig(numberOfNodes = 2, clusterProvider = "createClusterLowReadTimeout") public void should_not_receive_wrong_response_when_callbacks_block_io_thread() { assertThat(columnsToGrab.size()).isGreaterThan(1); final CountDownLatch errorTrigger = new CountDownLatch(1); if (errorTrigger.getCount() == 0) { fail( String.format( "Error triggered at or before %d of %d requests after %dms.", fail("Test interrupted", e); Uninterruptibles.awaitUninterruptibly(errorTrigger, 10, TimeUnit.SECONDS); if (errorTrigger.getCount() == 0) { fail(String.format("Error triggered after %dms.", System.currentTimeMillis() - start));
@Test(groups = "short") public void should_fail_in_borrowConnection_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS); fail("Should have thrown exception"); } catch (ExecutionException e) { assertThat(e.getCause()).isInstanceOf(DriverException.class); assertThat(e.getCause().getMessage()) .contains( "Aborting attempt to set keyspace to 'newks' since there is already an in flight attempt to set keyspace to 'slowks'.");
@Override public void run() { try (Session session = pool.getReadSession()) { failed.compareAndSet(false, session == null); Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS); } catch (SpannerException e) { failed.compareAndSet(false, true); } finally { latch.countDown(); } } })
@Test public void testCancelOutstandingRequest() throws Exception { Assert.assertTrue(_nettyTCPClientConnection.connect()); ResponseFuture responseFuture = _nettyTCPClientConnection .sendRequest(Unpooled.wrappedBuffer(NettyTestUtils.DUMMY_REQUEST.getBytes()), 1L, 5000L); responseFuture.cancel(false); // Wait for cancel taking effect Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS); Assert.assertNull(responseFuture.getOne()); Assert.assertTrue(responseFuture.isCancelled()); }
@Test public void testValidatePool() throws Exception { Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS); Assert.assertTrue(pool.validate(false)); PoolStats stats = pool.getStats(); Assert.assertEquals(stats.getPoolSize(), 2); Assert.assertEquals(stats.getTotalBadDestroyed(), 0); Assert.assertEquals(stats.getCheckedOut(), 0);
@Test public void testServerShutdownLeak() throws Exception { Assert.assertNotNull(keyedPool.checkoutObject(_clientServer, "none").getOne()); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Assert.assertEquals(stats.getPoolSize(), 3); Assert.assertEquals(stats.getIdleCount(), 2); Assert.assertEquals(stats.getCheckedOut(), 1); Assert.assertEquals(waitersQueue.size(), 0);
@Test public void testConcurrency() { Random random = new Random(); Uninterruptibles.joinUninterruptibly(thread); Assert.assertNotNull(hitCounter); Assert.assertEquals(hitCounter.getHitCount(), expectedHitCount);
@Test(invocationCount = 1_000, timeOut = 10_000) public void testConcurrentClose() { List<Type> types = ImmutableList.of(VARCHAR, BIGINT, BIGINT); OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanNodeId("test"), "values"); ValuesOperator source = new ValuesOperator(operatorContext, rowPagesBuilder(types) .addSequencePage(10, 20, 30, 40) .build()); Operator sink = createSinkOperator(types); Driver driver = Driver.createDriver(driverContext, source, sink); // let these threads race scheduledExecutor.submit(() -> driver.processFor(new Duration(1, TimeUnit.NANOSECONDS))); // don't want to call isFinishedInternal in processFor scheduledExecutor.submit(() -> driver.close()); while (!driverContext.isDone()) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS); } }
@Test(groups = "short") public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception { ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace", GuavaCompatibility.INSTANCE.sameThreadExecutor()); try { Uninterruptibles.getUninterruptibly(resultFuture); } catch (ExecutionException e) { assertThat(e.getCause()) .isInstanceOf(InvalidQueryException.class) .hasMessage("Keyspace 'wrong_keyspace' does not exist"); } }
@Test(groups = "unit") public void should_generate_incrementing_timestamps_on_clock_resync() { ThreadLocalMonotonicTimestampGenerator generator = for (int i = 0; i < 1001; i++) { next = generator.next(); assertEquals(next, previous + 1); previous = next; assertEquals(next, start + 1001); assertThat(appender.getNext()) .containsOnlyOnce("Clock skew detected:") Uninterruptibles.sleepUninterruptibly(1100, TimeUnit.MILLISECONDS);
@Test(groups = "short", dataProvider = "keyspace") public void should_chain_query_on_async_session_init_with_different_executor(String keyspace) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(1); ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, executor); Integer result = Uninterruptibles.getUninterruptibly(resultFuture); assertThat(result).isEqualTo(1); executor.shutdownNow(); }
@Test public void testAsyncClient() throws Exception { ListenableFuture<String> getBeforeFuture; ListenableFuture<String> getAfterFuture; ListenableFuture<Void> putFuture; try (DelayedMap.AsyncClient client = createClient(DelayedMap.AsyncClient.class, syncServer).get()) { getBeforeFuture = client.getValueSlowly(200, TimeUnit.MILLISECONDS, "testKey"); putFuture = client.putValueSlowly(400, TimeUnit.MILLISECONDS, "testKey", "testValue"); getAfterFuture = client.getValueSlowly(600, TimeUnit.MILLISECONDS, "testKey"); assertEquals(Uninterruptibles.getUninterruptibly(getBeforeFuture), "default"); assertEquals(Uninterruptibles.getUninterruptibly(getAfterFuture), "testValue"); Uninterruptibles.getUninterruptibly(putFuture); } }
@Override public void waitForObservers() { try { Scanner scanner = env.getConnector().createScanner(env.getTable(), env.getAuthorizations()); Notification.configureScanner(scanner); while (true) { long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp(); long ntfyCount = Iterables.size(scanner); long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp(); if (ntfyCount == 0 && ts1 == (ts2 - 1)) { break; } long sleepTime = ntfyCount / 2; sleepTime = Math.min(Math.max(10, sleepTime), 10000); Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.MILLISECONDS); } } catch (Exception e) { throw new RuntimeException(e); } }
@Override public V waitForValue() throws ExecutionException { return getUninterruptibly(futureValue); }