com.google.common.util.concurrent.ListenableFuture

Here are the examples of the java api class com.google.common.util.concurrent.ListenableFuture taken from open source projects.

1. AbstractConfiguredObjectTest#testOpenAwaitsChildToAttainState_ChildStateChangeSyncErrors()

View license
public void testOpenAwaitsChildToAttainState_ChildStateChangeSyncErrors() throws Exception {
    final TestCar car = recoverParentAndChild();
    // Check we can observe the recovered child from the parent
    assertEquals(1, car.getChildren(TestEngine.class).size());
    TestEngine engine = (TestEngine) car.getChildren(TestEngine.class).iterator().next();
    engine.setStateChangeException(new RuntimeException("child attain state exception"));
    ListenableFuture carFuture = car.openAsync();
    assertTrue("car open future has not completed", carFuture.isDone());
    carFuture.get();
    assertEquals(State.ERRORED, engine.getState());
}

2. AbstractConfiguredObjectTest#testOpenAwaitsChildToAttainState_ChildStateChangeAsyncErrors()

View license
public void testOpenAwaitsChildToAttainState_ChildStateChangeAsyncErrors() throws Exception {
    SettableFuture<Void> engineStateChangeControllingFuture = SettableFuture.create();
    final TestCar car = recoverParentAndChild();
    // Check we can observe the recovered child from the parent
    assertEquals(1, car.getChildren(TestEngine.class).size());
    TestEngine engine = (TestEngine) car.getChildren(TestEngine.class).iterator().next();
    engine.setStateChangeFuture(engineStateChangeControllingFuture);
    ListenableFuture carFuture = car.openAsync();
    assertFalse("car open future has completed before engine has attained state", carFuture.isDone());
    engineStateChangeControllingFuture.setException(new RuntimeException("child attain state exception"));
    assertTrue("car open future has not completed", carFuture.isDone());
    carFuture.get();
    assertEquals(State.ERRORED, engine.getState());
}

3. AbstractConfiguredObjectTest#testOpenAwaitsChildToAttainState()

View license
public void testOpenAwaitsChildToAttainState() throws Exception {
    SettableFuture<Void> engineStateChangeControllingFuture = SettableFuture.create();
    final TestCar car = recoverParentAndChild();
    // Check we can observe the recovered child from the parent
    assertEquals(1, car.getChildren(TestEngine.class).size());
    TestEngine engine = (TestEngine) car.getChildren(TestEngine.class).iterator().next();
    engine.setStateChangeFuture(engineStateChangeControllingFuture);
    ListenableFuture carFuture = car.openAsync();
    assertFalse("car open future has completed before engine has attained state", carFuture.isDone());
    engineStateChangeControllingFuture.set(null);
    assertTrue("car open future has not completed", carFuture.isDone());
    carFuture.get();
}

4. AbstractConfiguredObjectTest#testCloseAwaitsChildCloseCompletion()

View license
public void testCloseAwaitsChildCloseCompletion() {
    SettableFuture<Void> engineCloseControllingFuture = SettableFuture.create();
    TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"));
    String engineName = "myEngine";
    Map<String, Object> engineAttributes = new HashMap<>();
    engineAttributes.put(ConfiguredObject.NAME, engineName);
    engineAttributes.put(TestEngine.BEFORE_CLOSE_FUTURE, engineCloseControllingFuture);
    TestEngine engine = (TestEngine) car.createChild(TestEngine.class, engineAttributes);
    ListenableFuture carListenableFuture = car.closeAsync();
    assertFalse("car close future has completed before engine closed", carListenableFuture.isDone());
    assertSame("engine deregistered from car too early", engine, car.getChildById(TestEngine.class, engine.getId()));
    engineCloseControllingFuture.set(null);
    assertTrue("car close future has not completed", carListenableFuture.isDone());
    assertNull("engine not deregistered", car.getChildById(TestEngine.class, engine.getId()));
}

5. AbstractConfiguredObjectTest#testCreateAwaitsAttainState_StateChangeSyncErrors()

View license
public void testCreateAwaitsAttainState_StateChangeSyncErrors() throws Exception {
    RuntimeException stateChangeException = new RuntimeException("state change error");
    TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"));
    Map<String, Object> engineAttributes = new HashMap<>();
    engineAttributes.put(ConfiguredObject.NAME, "myEngine");
    engineAttributes.put(TestEngine.STATE_CHANGE_EXCEPTION, stateChangeException);
    ListenableFuture engine = car.createChildAsync(TestEngine.class, engineAttributes);
    assertTrue("create child has not completed", engine.isDone());
    try {
        engine.get();
        fail("Exception not thrown");
    } catch (ExecutionException ee) {
        assertSame(stateChangeException, ee.getCause());
    }
}

6. AbstractConfiguredObjectTest#testCreateAwaitsAttainState()

View license
public void testCreateAwaitsAttainState() {
    SettableFuture stateChangeFuture = SettableFuture.create();
    TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"));
    Map<String, Object> engineAttributes = new HashMap<>();
    engineAttributes.put(ConfiguredObject.NAME, "myEngine");
    engineAttributes.put(TestEngine.STATE_CHANGE_FUTURE, stateChangeFuture);
    ListenableFuture engine = car.createChildAsync(TestEngine.class, engineAttributes);
    assertFalse("create child has completed before state change completes", engine.isDone());
    stateChangeFuture.set(null);
    assertTrue("create child has not completed", engine.isDone());
}

7. TestEmbeddedSDCPool#testEmbeddedSDCTimeout()

View license
@Test(timeout = 90000)
public void testEmbeddedSDCTimeout() throws Exception {
    Properties props = new Properties();
    DummyEmbeddedSDCPool dummyEmbeddedSDCPool = new DummyEmbeddedSDCPool(props);
    Assert.assertEquals(1, dummyEmbeddedSDCPool.getInstances().size());
    Assert.assertEquals(1, dummyEmbeddedSDCPool.size());
    EmbeddedSDC embeddedSDC1 = dummyEmbeddedSDCPool.checkout();
    Assert.assertEquals(0, dummyEmbeddedSDCPool.size());
    // Nothing in pool, so wait() should return null
    assertNull(dummyEmbeddedSDCPool.waitForSDC(3000));
    ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));
    WaitOnSDCRunnable th = new WaitOnSDCRunnable(dummyEmbeddedSDCPool);
    ListenableFuture future = executorService.submit(th);
    Thread.sleep(100);
    // shouldn't be done yet
    assertTrue(!future.isDone());
    assertNull(th.embeddedSDC);
    // return back sdc to pool
    dummyEmbeddedSDCPool.checkin(embeddedSDC1);
    assertNull(future.get());
    assertEquals(embeddedSDC1, th.embeddedSDC);
}

8. AbstractConfiguredObjectTest#testGetChildren_NewChild()

View license
public void testGetChildren_NewChild() {
    TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"));
    String engineName = "myEngine";
    Map<String, Object> engineAttributes = new HashMap<>();
    engineAttributes.put(ConfiguredObject.NAME, engineName);
    TestEngine engine = (TestEngine) car.createChild(TestEngine.class, engineAttributes);
    // Check we can observe the new child from the parent
    assertEquals(1, car.getChildren(TestEngine.class).size());
    assertEquals(engine, car.getChildById(TestEngine.class, engine.getId()));
    assertEquals(engine, car.getChildByName(TestEngine.class, engine.getName()));
    ListenableFuture attainedChild = car.getAttainedChildByName(TestEngine.class, engine.getName());
    assertNotNull(attainedChild);
    assertTrue("Engine should have already attained state", attainedChild.isDone());
}

9. AbstractConfiguredObjectTest#testGetChildren_RecoveredChild()

View license
public void testGetChildren_RecoveredChild() throws Exception {
    final TestCar car = recoverParentAndChild();
    // Check we can observe the recovered child from the parent
    assertEquals(1, car.getChildren(TestEngine.class).size());
    TestEngine engine = (TestEngine) car.getChildren(TestEngine.class).iterator().next();
    assertEquals(engine, car.getChildById(TestEngine.class, engine.getId()));
    assertEquals(engine, car.getChildByName(TestEngine.class, engine.getName()));
    ListenableFuture attainedChild = car.getAttainedChildByName(TestEngine.class, engine.getName());
    assertNotNull(attainedChild);
    assertFalse("Engine should not have yet attained state", attainedChild.isDone());
    car.open();
    assertTrue("Engine should have now attained state", attainedChild.isDone());
    assertEquals(engine, attainedChild.get());
}

10. ChainedExecutionQueryRunnerTest#testQueryCancellation()

View license
@Test(timeout = 60000)
public void testQueryCancellation() throws Exception {
    ExecutorService exec = PrioritizedExecutorService.create(new Lifecycle(), new DruidProcessingConfig() {

        @Override
        public String getFormatString() {
            return "test";
        }

        @Override
        public int getNumThreads() {
            return 2;
        }
    });
    final CountDownLatch queriesStarted = new CountDownLatch(2);
    final CountDownLatch queriesInterrupted = new CountDownLatch(2);
    final CountDownLatch queryIsRegistered = new CountDownLatch(1);
    Capture<ListenableFuture> capturedFuture = EasyMock.newCapture();
    QueryWatcher watcher = EasyMock.createStrictMock(QueryWatcher.class);
    watcher.registerQuery(EasyMock.<Query>anyObject(), EasyMock.and(EasyMock.<ListenableFuture>anyObject(), EasyMock.capture(capturedFuture)));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {

        @Override
        public Void answer() throws Throwable {
            queryIsRegistered.countDown();
            return null;
        }
    }).once();
    EasyMock.replay(watcher);
    ArrayBlockingQueue<DyingQueryRunner> interrupted = new ArrayBlockingQueue<>(3);
    Set<DyingQueryRunner> runners = Sets.newHashSet(new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted), new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted), new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted));
    ChainedExecutionQueryRunner chainedRunner = new ChainedExecutionQueryRunner<>(exec, watcher, Lists.<QueryRunner<Integer>>newArrayList(runners));
    Map<String, Object> context = ImmutableMap.<String, Object>of();
    final Sequence seq = chainedRunner.run(Druids.newTimeseriesQueryBuilder().dataSource("test").intervals("2014/2015").aggregators(Lists.<AggregatorFactory>newArrayList(new CountAggregatorFactory("count"))).build(), context);
    Future resultFuture = Executors.newFixedThreadPool(1).submit(new Runnable() {

        @Override
        public void run() {
            Sequences.toList(seq, Lists.newArrayList());
        }
    });
    // wait for query to register and start
    queryIsRegistered.await();
    queriesStarted.await();
    // cancel the query
    Assert.assertTrue(capturedFuture.hasCaptured());
    ListenableFuture future = capturedFuture.getValue();
    future.cancel(true);
    QueryInterruptedException cause = null;
    try {
        resultFuture.get();
    } catch (ExecutionException e) {
        Assert.assertTrue(e.getCause() instanceof QueryInterruptedException);
        cause = (QueryInterruptedException) e.getCause();
    }
    queriesInterrupted.await();
    Assert.assertNotNull(cause);
    Assert.assertTrue(future.isCancelled());
    DyingQueryRunner interrupted1 = interrupted.poll();
    synchronized (interrupted1) {
        Assert.assertTrue("runner 1 started", interrupted1.hasStarted);
        Assert.assertTrue("runner 1 interrupted", interrupted1.interrupted);
    }
    DyingQueryRunner interrupted2 = interrupted.poll();
    synchronized (interrupted2) {
        Assert.assertTrue("runner 2 started", interrupted2.hasStarted);
        Assert.assertTrue("runner 2 interrupted", interrupted2.interrupted);
    }
    runners.remove(interrupted1);
    runners.remove(interrupted2);
    DyingQueryRunner remainingRunner = runners.iterator().next();
    synchronized (remainingRunner) {
        Assert.assertTrue("runner 3 should be interrupted or not have started", !remainingRunner.hasStarted || remainingRunner.interrupted);
    }
    Assert.assertFalse("runner 1 not completed", interrupted1.hasCompleted);
    Assert.assertFalse("runner 2 not completed", interrupted2.hasCompleted);
    Assert.assertFalse("runner 3 not completed", remainingRunner.hasCompleted);
    EasyMock.verify(watcher);
}

11. AnyFuture#cancelOthers()

Project: ethereumj
Source File: AnyFuture.java
View license
private void cancelOthers(ListenableFuture besidesThis) {
    for (ListenableFuture future : futures) {
        if (future != besidesThis) {
            try {
                future.cancel(true);
            } catch (Exception e) {
            }
        }
    }
}

12. AbstractConfiguredObjectTest#testCreateAwaitsAttainState_StateChangeAsyncErrors()

View license
public void testCreateAwaitsAttainState_StateChangeAsyncErrors() throws Exception {
    SettableFuture stateChangeFuture = SettableFuture.create();
    RuntimeException stateChangeException = new RuntimeException("state change error");
    TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"));
    Map<String, Object> engineAttributes = new HashMap<>();
    engineAttributes.put(ConfiguredObject.NAME, "myEngine");
    engineAttributes.put(TestEngine.STATE_CHANGE_FUTURE, stateChangeFuture);
    ListenableFuture engine = car.createChildAsync(TestEngine.class, engineAttributes);
    assertFalse("create child has completed before state change completes", engine.isDone());
    stateChangeFuture.setException(stateChangeException);
    assertTrue("create child has not completed", engine.isDone());
    try {
        engine.get();
        fail("Exception not thrown");
    } catch (ExecutionException ee) {
        assertSame(stateChangeException, ee.getCause());
    }
}

13. QueryResourceTest#testDenySecuredGetServer()

Project: druid
Source File: QueryResourceTest.java
View license
@Test(timeout = 60_000L)
public void testDenySecuredGetServer() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(EasyMock.anyString())).andReturn(new AuthorizationInfo() {

        @Override
        public Access isAuthorized(Resource resource, Action action) {
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
                try {
                    waitForCancellationLatch.await();
                } catch (InterruptedException e) {
                    Throwables.propagate(e);
                }
                return new Access(true);
            } else {
                // Deny access to cancel the query
                return new Access(false);
            }
        }
    }).times(2);
    EasyMock.replay(testServletRequest);
    queryResource = new QueryResource(serverConfig, jsonMapper, jsonMapper, testSegmentWalker, new NoopServiceEmitter(), new NoopRequestLogger(), queryManager, new AuthConfig(true));
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);
    ListenableFuture future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                startAwaitLatch.countDown();
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes("UTF-8")), null, testServletRequest);
                Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                Throwables.propagate(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryManager.registerQuery(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            Response response = queryResource.getServer("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
        }
    });
    waitFinishLatch.await();
}

14. QueryResourceTest#testSecuredGetServer()

Project: druid
Source File: QueryResourceTest.java
View license
@Test(timeout = 60_000L)
public void testSecuredGetServer() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    final CountDownLatch cancelledCountDownLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(EasyMock.anyString())).andReturn(new AuthorizationInfo() {

        @Override
        public Access isAuthorized(Resource resource, Action action) {
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
                try {
                    waitForCancellationLatch.await();
                } catch (InterruptedException e) {
                    cancelledCountDownLatch.countDown();
                    Throwables.propagate(e);
                }
                return new Access(true);
            } else {
                return new Access(true);
            }
        }
    }).times(2);
    EasyMock.replay(testServletRequest);
    queryResource = new QueryResource(serverConfig, jsonMapper, jsonMapper, testSegmentWalker, new NoopServiceEmitter(), new NoopRequestLogger(), queryManager, new AuthConfig(true));
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);
    ListenableFuture future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                startAwaitLatch.countDown();
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes("UTF-8")), null, testServletRequest);
                Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                Throwables.propagate(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryManager.registerQuery(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            Response response = queryResource.getServer("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
        }
    });
    waitFinishLatch.await();
    cancelledCountDownLatch.await();
}

15. QueryManager#cancelQuery()

Project: druid
Source File: QueryManager.java
View license
public boolean cancelQuery(String id) {
    queryDatasources.removeAll(id);
    Set<ListenableFuture> futures = queries.removeAll(id);
    boolean success = true;
    for (ListenableFuture future : futures) {
        success = success && future.cancel(true);
    }
    return success;
}

16. LookupCoordinatorManager#updateNodes()

Project: druid
Source File: LookupCoordinatorManager.java
View license
void updateNodes(Collection<URL> urls, final Map<String, Map<String, Object>> knownLookups) throws IOException, InterruptedException, ExecutionException {
    if (knownLookups == null) {
        LOG.debug("No config for lookups found");
        return;
    }
    if (knownLookups.isEmpty()) {
        LOG.debug("No known lookups. Skipping update");
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Updating %d lookups on %d nodes", knownLookups.size(), urls.size());
    }
    final List<ListenableFuture<?>> futures = new ArrayList<>(urls.size());
    for (final URL url : urls) {
        futures.add(executorService.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    updateAllOnHost(url, knownLookups);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    LOG.warn("Update on [%s] interrupted", url);
                    throw Throwables.propagate(e);
                } catch (IOExceptionExecutionException |  e) {
                    LOG.makeAlert(e, "Error submitting to [%s]", url).emit();
                }
            }
        }));
    }
    final ListenableFuture allFuture = Futures.allAsList(futures);
    try {
        allFuture.get(lookupCoordinatorManagerConfig.getUpdateAllTimeout().getMillis(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        LOG.warn("Timeout in updating hosts! Attempting to cancel");
        allFuture.cancel(true);
    }
}

17. LookupCoordinatorManager#deleteAllOnTier()

Project: druid
Source File: LookupCoordinatorManager.java
View license
void deleteAllOnTier(final String tier, final Collection<String> dropLookups) throws ExecutionException, InterruptedException, IOException {
    if (dropLookups.isEmpty()) {
        LOG.debug("Nothing to drop");
        return;
    }
    final Collection<URL> urls = getAllHostsAnnounceEndpoint(tier);
    final List<ListenableFuture<?>> futures = new ArrayList<>(urls.size());
    for (final URL url : urls) {
        futures.add(executorService.submit(new Runnable() {

            @Override
            public void run() {
                for (final String drop : dropLookups) {
                    final URL lookupURL;
                    try {
                        lookupURL = new URL(url.getProtocol(), url.getHost(), url.getPort(), String.format("%s/%s", url.getFile(), drop));
                    } catch (MalformedURLException e) {
                        throw new ISE(e, "Error creating url for [%s]/[%s]", url, drop);
                    }
                    try {
                        deleteOnHost(lookupURL);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        LOG.warn("Delete [%s] interrupted", lookupURL);
                        throw Throwables.propagate(e);
                    } catch (IOExceptionExecutionException |  e) {
                        LOG.makeAlert(e, "Error deleting [%s]", lookupURL).emit();
                    }
                }
            }
        }));
    }
    final ListenableFuture allFuture = Futures.allAsList(futures);
    try {
        allFuture.get(lookupCoordinatorManagerConfig.getUpdateAllTimeout().getMillis(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        allFuture.cancel(true);
        throw new ExecutionException("Timeout in updating hosts! Attempting to cancel", e);
    }
}

18. ChainedExecutionQueryRunnerTest#testQueryTimeout()

View license
@Test(timeout = 60000)
public void testQueryTimeout() throws Exception {
    ExecutorService exec = PrioritizedExecutorService.create(new Lifecycle(), new DruidProcessingConfig() {

        @Override
        public String getFormatString() {
            return "test";
        }

        @Override
        public int getNumThreads() {
            return 2;
        }
    });
    final CountDownLatch queriesStarted = new CountDownLatch(2);
    final CountDownLatch queriesInterrupted = new CountDownLatch(2);
    final CountDownLatch queryIsRegistered = new CountDownLatch(1);
    Capture<ListenableFuture> capturedFuture = new Capture<>();
    QueryWatcher watcher = EasyMock.createStrictMock(QueryWatcher.class);
    watcher.registerQuery(EasyMock.<Query>anyObject(), EasyMock.and(EasyMock.<ListenableFuture>anyObject(), EasyMock.capture(capturedFuture)));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {

        @Override
        public Void answer() throws Throwable {
            queryIsRegistered.countDown();
            return null;
        }
    }).once();
    EasyMock.replay(watcher);
    ArrayBlockingQueue<DyingQueryRunner> interrupted = new ArrayBlockingQueue<>(3);
    Set<DyingQueryRunner> runners = Sets.newHashSet(new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted), new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted), new DyingQueryRunner(queriesStarted, queriesInterrupted, interrupted));
    ChainedExecutionQueryRunner chainedRunner = new ChainedExecutionQueryRunner<>(exec, watcher, Lists.<QueryRunner<Integer>>newArrayList(runners));
    HashMap<String, Object> context = new HashMap<String, Object>();
    final Sequence seq = chainedRunner.run(Druids.newTimeseriesQueryBuilder().dataSource("test").intervals("2014/2015").aggregators(Lists.<AggregatorFactory>newArrayList(new CountAggregatorFactory("count"))).context(ImmutableMap.<String, Object>of(QueryContextKeys.TIMEOUT, 100, "queryId", "test")).build(), context);
    Future resultFuture = Executors.newFixedThreadPool(1).submit(new Runnable() {

        @Override
        public void run() {
            Sequences.toList(seq, Lists.newArrayList());
        }
    });
    // wait for query to register and start
    queryIsRegistered.await();
    queriesStarted.await();
    Assert.assertTrue(capturedFuture.hasCaptured());
    ListenableFuture future = capturedFuture.getValue();
    // wait for query to time out
    QueryInterruptedException cause = null;
    try {
        resultFuture.get();
    } catch (ExecutionException e) {
        Assert.assertTrue(e.getCause() instanceof QueryInterruptedException);
        Assert.assertEquals("Query timeout", e.getCause().getMessage());
        cause = (QueryInterruptedException) e.getCause();
    }
    queriesInterrupted.await();
    Assert.assertNotNull(cause);
    Assert.assertTrue(future.isCancelled());
    DyingQueryRunner interrupted1 = interrupted.poll();
    synchronized (interrupted1) {
        Assert.assertTrue("runner 1 started", interrupted1.hasStarted);
        Assert.assertTrue("runner 1 interrupted", interrupted1.interrupted);
    }
    DyingQueryRunner interrupted2 = interrupted.poll();
    synchronized (interrupted2) {
        Assert.assertTrue("runner 2 started", interrupted2.hasStarted);
        Assert.assertTrue("runner 2 interrupted", interrupted2.interrupted);
    }
    runners.remove(interrupted1);
    runners.remove(interrupted2);
    DyingQueryRunner remainingRunner = runners.iterator().next();
    synchronized (remainingRunner) {
        Assert.assertTrue("runner 3 should be interrupted or not have started", !remainingRunner.hasStarted || remainingRunner.interrupted);
    }
    Assert.assertFalse("runner 1 not completed", interrupted1.hasCompleted);
    Assert.assertFalse("runner 2 not completed", interrupted2.hasCompleted);
    Assert.assertFalse("runner 3 not completed", remainingRunner.hasCompleted);
    EasyMock.verify(watcher);
}

19. NamespaceExtractionCacheManagerExecutorsTest#testShutdown()

View license
@Test(timeout = 60_000)
public void testShutdown() throws NoSuchFieldException, IllegalAccessException, InterruptedException, ExecutionException {
    final long period = 5L;
    final ListenableFuture future;
    long prior = 0;
    final String namespaceID = "ns";
    try {
        final URIExtractionNamespace namespace = new URIExtractionNamespace(tmpFile.toURI(), null, null, new URIExtractionNamespace.ObjectMapperFlatDataParser(URIExtractionNamespaceTest.registerTypes(new ObjectMapper())), new Period(period), null);
        cacheUpdateAlerts.putIfAbsent(namespaceID, new Object());
        future = manager.schedule(namespaceID, namespace);
        final Object cacheUpdateAlerter = cacheUpdateAlerts.get(namespaceID);
        synchronized (cacheUpdateAlerter) {
            cacheUpdateAlerter.wait();
        }
        Assert.assertFalse(future.isCancelled());
        Assert.assertFalse(future.isDone());
        synchronized (cacheUpdateAlerter) {
            prior = numRuns.get();
            cacheUpdateAlerter.wait();
        }
        Assert.assertTrue(numRuns.get() > prior);
    } finally {
        lifecycle.stop();
    }
    while (!manager.waitForServiceToEnd(1_000, TimeUnit.MILLISECONDS)) {
    }
    checkNoMoreRunning();
    Field execField = NamespaceExtractionCacheManager.class.getDeclaredField("listeningScheduledExecutorService");
    execField.setAccessible(true);
    Assert.assertTrue(((ListeningScheduledExecutorService) execField.get(manager)).isShutdown());
    Assert.assertTrue(((ListeningScheduledExecutorService) execField.get(manager)).isTerminated());
}