Example usage for java.util.concurrent ExecutorService awaitTermination

List of usage examples for java.util.concurrent ExecutorService awaitTermination

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService awaitTermination.

Prototype

boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Usage

From source file:org.wso2.appserver.integration.lazy.loading.artifacts.SuperTenantGhostDeploymentTestCase.java

@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests  when Web-App is in Ghost form. "
        + "All request should  get expected output", dependsOnMethods = "testWebAppAutoUnLoadAndReloadInGhostFormInGhostDeploymentOnSuperTenant", enabled = false)
public void testConcurrentWebAPPInvocationsWhenWebAppIsInGhostFormInGhostDeploymentOnSuperTenant()
        throws Exception {
    //This test method case disable because of CARBON-15271
    serverManager.restartGracefully();//ww w.j  av  a 2s  .  c  o  m
    HttpResponse httpResponseApp2 = HttpURLConnectionClient.sendGetRequest(webApp2URL, null);
    assertTrue(httpResponseApp2.getData().contains(WEB_APP2_RESPONSE),
            "Invocation of Web-App fail :" + webApp2URL);
    WebAppStatusBean webAppStatusTenant1WebApp2 = getWebAppStatus(superTenantDomain, WEB_APP_FILE_NAME2);
    assertTrue(webAppStatusTenant1WebApp2.isWebAppStarted(),
            "Web-App: " + WEB_APP_FILE_NAME2 + " is not started in Tenant:" + superTenantDomain);
    assertFalse(webAppStatusTenant1WebApp2.isWebAppGhost(), "Web-App: " + WEB_APP_FILE_NAME2
            + " is in ghost mode after invoking in Tenant:" + superTenantDomain);
    WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(superTenantDomain, WEB_APP_FILE_NAME1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + WEB_APP_FILE_NAME1 + " is not started in Tenant:" + superTenantDomain);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + WEB_APP_FILE_NAME1
            + " is in not ghost mode before invoking in Tenant:" + superTenantDomain);
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT);
    log.info("Concurrent invocation Start");
    log.info("Expected Response Data:" + WEB_APP1_RESPONSE);
    for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) {
        final int requestId = i;
        executorService.execute(new Runnable() {

            public void run() {
                HttpResponse httpResponse = null;
                try {
                    httpResponse = HttpURLConnectionClient.sendGetRequest(webApp1URL, null);
                } catch (IOException e) {
                    log.error("Error  when sending a  get request  for :" + webApp1URL, e);
                }
                synchronized (this) {
                    String responseDetailedInfo;
                    String responseData;
                    if (httpResponse != null) {
                        responseDetailedInfo = "Request ID " + requestId + " Response Data :"
                                + httpResponse.getData() + "\tResponse Code:" + httpResponse.getResponseCode();
                        responseData = httpResponse.getData();
                    } else {
                        responseDetailedInfo = "Request ID " + requestId
                                + " Response Data : NULL Object return from" + " HttpURLConnectionClient";
                        responseData = "NULL Object return";
                    }
                    responseDataList.add(responseData);
                    log.info(responseDetailedInfo);
                    responseDetailedInfoList.add(responseDetailedInfo);
                }
            }

        });
    }
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    log.info("Concurrent invocation End");
    int correctResponseCount = 0;
    for (String responseData : responseDataList) {
        if (WEB_APP1_RESPONSE.equals(responseData)) {
            correctResponseCount += 1;
        }
    }
    StringBuilder allDetailResponseStringBuffer = new StringBuilder();
    allDetailResponseStringBuffer.append("\n");
    for (String responseInfo : responseDetailedInfoList) {
        allDetailResponseStringBuffer.append(responseInfo);
        allDetailResponseStringBuffer.append("\n");
    }
    String allDetailResponse = allDetailResponseStringBuffer.toString();
    webAppStatusTenant1WebApp1 = getWebAppStatus(superTenantDomain, WEB_APP_FILE_NAME1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + WEB_APP_FILE_NAME1 + " is not started in Tenant:" + superTenantDomain);
    assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + WEB_APP_FILE_NAME1
            + " is in ghost mode after invoking in Tenant:" + superTenantDomain);
    assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT,
            allDetailResponse + "All the concurrent requests not get correct response.");
}

From source file:org.wso2.appserver.integration.lazy.loading.artifacts.JaggeryApplicationGhostDeploymentTestCase.java

@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests  when tenant context is not loaded."
        + "All request should  get expected output", dependsOnMethods = "testTenantUnloadInIdleTimeAfterJaggeryAPPUsageInGhostDeployment", enabled = false)
public void testConcurrentJaggeryAPPInvocationsWhenTenantContextNotLoadedInGhostDeployment() throws Exception {
    serverManager.restartGracefully();//from   w ww . j  a  va 2 s.  co m
    assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  loaded before access. Tenant name: " + tenantDomain1);
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT);
    log.info("Concurrent invocation Start");
    log.info("Expected Response Data:" + JAGG_APP1_RESPONSE);
    for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) {
        executorService.execute(new Runnable() {

            public void run() {
                HttpResponse httpResponse = null;
                try {
                    httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1JaggApp1Url, null);
                } catch (IOException e) {
                    log.error("Error  when sending a  get request  for :" + tenant1JaggApp1Url, e);
                }
                synchronized (this) {
                    String responseDetailedInfo;
                    String responseData;
                    if (httpResponse != null) {
                        responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:"
                                + httpResponse.getResponseCode();
                        responseData = httpResponse.getData();
                    } else {
                        responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient";
                        responseData = "NULL Object return";
                    }
                    responseDataList.add(responseData);
                    log.info(responseDetailedInfo);
                    responseDetailedInfoList.add(responseDetailedInfo);
                }
            }

        });
    }
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    log.info("Concurrent invocation End");
    int correctResponseCount = 0;
    for (String responseData : responseDataList) {
        if (JAGG_APP1_RESPONSE.equals(responseData)) {
            correctResponseCount += 1;
        }
    }
    StringBuffer allDetailResponseStringBuffer = new StringBuffer();
    allDetailResponseStringBuffer.append("\n");
    for (String responseInfo : responseDetailedInfoList) {
        allDetailResponseStringBuffer.append(responseInfo);
        allDetailResponseStringBuffer.append("\n");
    }
    String allDetailResponse = allDetailResponseStringBuffer.toString();
    WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, JAGGERY_APP_NAME1);
    assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(),
            " Tenant Context is not loaded. Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + JAGGERY_APP_NAME1 + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(),
            "Web-App: " + JAGGERY_APP_NAME1 + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT,
            allDetailResponse + "All the concurrent requests " + "not get correct response.");

}

From source file:org.wso2.appserver.integration.lazy.loading.artifacts.CarbonAppGhostDeploymentTestCase.java

@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests  when tenant context is loaded."
        + " But Web-App  that is deployed as Carbon application is in Ghost form. All request should  get expected output", dependsOnMethods = "testConcurrentWebAPPInCarbonAppInvocationsWhenTenantContextNotLoadedInGhostDeployment", enabled = false)
public void testConcurrentWebAPPInCarbonAppInvocationsWhenTenantContextLoadedInGhostDeployment()
        throws Exception {
    //This test method case disable because of CARBON-15270
    serverManager.restartGracefully();//from   w ww.  j  av  a 2 s.  c  om
    responseDataList.clear();
    responseDetailedInfoList.clear();
    assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  loaded before access. Tenant name: " + tenantDomain1);
    HttpResponse httpResponseApp2 = HttpURLConnectionClient.sendGetRequest(tenant1WebApp2URL, null);
    assertTrue(httpResponseApp2.getData().contains(WEB_APP2_RESPONSE),
            "Invocation of Web-App fail :" + tenant1WebApp2URL);
    assertTrue(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  not loaded after access. Tenant name: " + tenantDomain1);
    WebAppStatusBean webAppStatusTenant1WebApp2 = getWebAppStatus(tenantDomain1, CARBON_APP2_WEB_APP_FILE);
    assertTrue(webAppStatusTenant1WebApp2.isWebAppStarted(),
            "Web-App: " + CARBON_APP2_WEB_APP_FILE + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp2.isWebAppGhost(), "Web-App: " + CARBON_APP2_WEB_APP_FILE
            + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, CARBON_APP1_WEB_APP_FILE);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + CARBON_APP1_WEB_APP_FILE + " is not started in Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + CARBON_APP1_WEB_APP_FILE
            + " is in not ghost mode before invoking in Tenant:" + tenantDomain1);
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT);
    log.info("Concurrent invocation Start");
    log.info("Expected Response Data:" + WEB_APP1_RESPONSE);
    for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) {
        executorService.execute(new Runnable() {

            public void run() {
                HttpResponse httpResponse = null;
                try {
                    httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1WebApp1URL, null);
                } catch (IOException e) {
                    log.error("Error  when sending a  get request  for :" + tenant1WebApp1URL, e);
                }
                synchronized (this) {
                    String responseDetailedInfo;
                    String responseData;
                    if (httpResponse != null) {
                        responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:"
                                + httpResponse.getResponseCode();
                        responseData = httpResponse.getData();
                    } else {
                        responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient";
                        responseData = "NULL Object return";
                    }
                    responseDataList.add(responseData);
                    log.info(responseDetailedInfo);
                    responseDetailedInfoList.add(responseDetailedInfo);
                }
            }

        });
    }
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    log.info("Concurrent invocation End");
    int correctResponseCount = 0;
    for (String responseData : responseDataList) {
        if (WEB_APP1_RESPONSE.equals(responseData)) {
            correctResponseCount += 1;
        }
    }
    StringBuilder allDetailResponseStringBuffer = new StringBuilder();
    allDetailResponseStringBuffer.append("\n");
    for (String responseInfo : responseDetailedInfoList) {
        allDetailResponseStringBuffer.append(responseInfo);
        allDetailResponseStringBuffer.append("\n");
    }
    String allDetailResponse = allDetailResponseStringBuffer.toString();
    webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, CARBON_APP1_WEB_APP_FILE);
    assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(),
            " Tenant Context is" + " not loaded. Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + CARBON_APP1_WEB_APP_FILE + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + CARBON_APP1_WEB_APP_FILE
            + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT,
            allDetailResponse + "All the concurrent requests" + " not get correct response.");
}

From source file:org.wso2.appserver.integration.lazy.loading.artifacts.CarbonAppGhostDeploymentTestCase.java

@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests  when tenant context is not loaded."
        + "All request should  get expected output", dependsOnMethods = "testTenantUnloadInIdleTimeAfterWebAPPInCarbonAppUsageInGhostDeployment", enabled = false)
public void testConcurrentWebAPPInCarbonAppInvocationsWhenTenantContextNotLoadedInGhostDeployment()
        throws Exception {
    serverManager.restartGracefully();/*from   w w  w .  j  a v a 2 s . c o  m*/
    assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  loaded before access. Tenant name: " + tenantDomain1);
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT);
    log.info("Concurrent invocation Start");
    log.info("Expected Response Data:" + WEB_APP1_RESPONSE);
    for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) {
        executorService.execute(new Runnable() {

            public void run() {
                HttpResponse httpResponse = null;
                try {
                    httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1WebApp1URL, null);
                } catch (IOException ioException) {
                    log.error("Error  when sending a  get request  for :" + tenant1WebApp1URL, ioException);
                }
                synchronized (this) {
                    String responseDetailedInfo;
                    String responseData;
                    if (httpResponse != null) {
                        responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:"
                                + httpResponse.getResponseCode();
                        responseData = httpResponse.getData();
                    } else {
                        responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient";
                        responseData = "NULL Object return ";
                    }
                    responseDataList.add(responseData);
                    log.info(responseDetailedInfo);
                    responseDetailedInfoList.add(responseDetailedInfo);
                }
            }

        });
    }
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    log.info("Concurrent invocation End");
    int correctResponseCount = 0;
    for (String responseData : responseDataList) {
        if (WEB_APP1_RESPONSE.equals(responseData)) {
            correctResponseCount += 1;
        }
    }
    StringBuilder allDetailResponseStringBuffer = new StringBuilder();
    allDetailResponseStringBuffer.append("\n");
    for (String responseInfo : responseDetailedInfoList) {
        allDetailResponseStringBuffer.append(responseInfo);
        allDetailResponseStringBuffer.append("\n");
    }
    String allDetailResponse = allDetailResponseStringBuffer.toString();
    WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, CARBON_APP1_WEB_APP_FILE);
    assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(),
            " Tenant Context is" + " not loaded. Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + CARBON_APP1_WEB_APP_FILE + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + CARBON_APP1_WEB_APP_FILE
            + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT,
            allDetailResponse + "All the concurrent requests " + "not get correct response.");

}

From source file:org.wso2.appserver.integration.lazy.loading.artifacts.JaggeryApplicationGhostDeploymentTestCase.java

@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests  when tenant context is loaded."
        + " But Jaggery application is in Ghost form. All request should  get expected output", dependsOnMethods = "testConcurrentJaggeryAPPInvocationsWhenTenantContextNotLoadedInGhostDeployment", enabled = false)
public void testConcurrentJaggeryAPPInvocationsWhenTenantContextLoadedInGhostDeployment() throws Exception {
    //This test method case disable because of CARBON-15270
    serverManager.restartGracefully();//from  w  w w.  j  av  a2 s.c  o m
    responseDataList.clear();
    responseDetailedInfoList.clear();
    assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  loaded before access. Tenant name: " + tenantDomain1);
    HttpResponse httpResponseApp2 = HttpURLConnectionClient.sendGetRequest(tenant1JaggApp2Url, null);
    assertTrue(httpResponseApp2.getData().contains(JAGG_APP2_RESPONSE),
            "Invocation of Web-App fail :" + tenant1JaggApp2Url);
    assertTrue(getTenantStatus(tenantDomain1).isTenantContextLoaded(),
            "Tenant context is  not loaded after access. Tenant name: " + tenantDomain1);
    WebAppStatusBean webAppStatusTenant1WebApp2 = getWebAppStatus(tenantDomain1, JAGGERY_APP_NAME2);
    assertTrue(webAppStatusTenant1WebApp2.isWebAppStarted(),
            "Web-App: " + JAGGERY_APP_NAME2 + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp2.isWebAppGhost(),
            "Web-App: " + JAGGERY_APP_NAME2 + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, JAGGERY_APP_NAME1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + JAGGERY_APP_NAME1 + " is not started in Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + JAGGERY_APP_NAME1
            + " is in not ghost mode before invoking in Tenant:" + tenantDomain1);
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT);
    log.info("Concurrent invocation Start");
    log.info("Expected Response Data:" + JAGG_APP1_RESPONSE);
    for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) {
        executorService.execute(new Runnable() {

            public void run() {
                HttpResponse httpResponse = null;
                try {
                    httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1JaggApp1Url, null);
                } catch (IOException e) {
                    log.error("Error  when sending a  get request  for :" + tenant1JaggApp1Url, e);
                }
                synchronized (this) {
                    String responseDetailedInfo;
                    String responseData;
                    if (httpResponse != null) {
                        responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:"
                                + httpResponse.getResponseCode();
                        responseData = httpResponse.getData();
                    } else {
                        responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient";
                        responseData = "NULL Object return";
                    }
                    responseDataList.add(responseData);
                    log.info(responseDetailedInfo);
                    responseDetailedInfoList.add(responseDetailedInfo);
                }
            }

        });
    }
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    log.info("Concurrent invocation End");
    int correctResponseCount = 0;
    for (String responseData : responseDataList) {
        if (JAGG_APP1_RESPONSE.equals(responseData)) {
            correctResponseCount += 1;
        }
    }
    StringBuilder allDetailResponseStringBuffer = new StringBuilder();
    allDetailResponseStringBuffer.append("\n");

    for (String responseInfo : responseDetailedInfoList) {
        allDetailResponseStringBuffer.append(responseInfo);
        allDetailResponseStringBuffer.append("\n");
    }
    String allDetailResponse = allDetailResponseStringBuffer.toString();
    webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, JAGGERY_APP_NAME1);
    assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(),
            " Tenant Context is not loaded. Tenant:" + tenantDomain1);
    assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(),
            "Web-App: " + JAGGERY_APP_NAME1 + " is not started in Tenant:" + tenantDomain1);
    assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(),
            "Web-App: " + JAGGERY_APP_NAME1 + " is in ghost mode after invoking in Tenant:" + tenantDomain1);
    assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT,
            allDetailResponse + "All the concurrent requests" + " not get correct response.");

}

From source file:org.wso2.carbon.analytics.dataservice.core.indexing.AnalyticsDataIndexer.java

private void shutdownTaxonomyWorkerThreadPool(ExecutorService pool) throws AnalyticsIndexException {
    if (pool != null) {
        pool.shutdown();//  w  w w.ja v  a  2  s.  c o m
    }
    try {
        if (!pool.awaitTermination(TAXONOMYWORKER_TIMEOUT, TimeUnit.SECONDS)) {
            pool.shutdownNow();
        }
    } catch (InterruptedException e) {
        log.error("Error while shutting down the Taxonomyworker threadpool , " + e.getMessage(), e);
        throw new AnalyticsIndexException(
                "Error while shutting down the Taxonomyworker threadpool , " + e.getMessage(), e);
    } finally {
        pool = null;
    }
}

From source file:io.undertow.servlet.test.streams.AbstractServletInputStreamTestCase.java

public void runTestParallel(int concurrency, final String message, String url, boolean preamble,
        boolean offIOThread) throws Exception {

    CloseableHttpClient client = HttpClients.custom().setMaxConnPerRoute(1000)
            .setSSLContext(DefaultServer.createClientSslContext()).build();
    byte[] messageBytes = message.getBytes();
    try {/* w  w w.  j  a v  a 2  s.c o m*/
        ExecutorService executorService = Executors.newFixedThreadPool(concurrency);
        Callable task = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                String uri = getBaseUrl() + "/servletContext/" + url;
                HttpPost post = new HttpPost(uri);
                if (preamble && !message.isEmpty()) {
                    post.addHeader("preamble", Integer.toString(message.length() / 2));
                }
                if (offIOThread) {
                    post.addHeader("offIoThread", "true");
                }
                post.setEntity(new InputStreamEntity(
                        // Server should wait for events from the client
                        new RateLimitedInputStream(new ByteArrayInputStream(messageBytes))));
                CloseableHttpResponse result = client.execute(post);
                try {
                    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                    final String response = HttpClientUtils.readResponse(result);
                    Assert.assertEquals(message.length(), response.length());
                    Assert.assertEquals(message, response);
                } finally {
                    result.close();
                }
                return null;
            }
        };
        List<Future<?>> results = new ArrayList<>();
        for (int i = 0; i < concurrency * 5; i++) {
            Future<?> future = executorService.submit(task);
            results.add(future);
        }
        for (Future<?> i : results) {
            i.get();
        }
        executorService.shutdown();
        Assert.assertTrue(executorService.awaitTermination(70, TimeUnit.SECONDS));
    } finally {
        client.close();
    }
}

From source file:org.apache.phoenix.execute.UpsertSelectOverlappingBatchesIT.java

/**
 * Tests that UPSERT SELECT doesn't indefinitely block region closes
 *//*from  w w w .  j  ava2 s  . co  m*/
@Test
public void testRegionCloseDuringUpsertSelect() throws Exception {
    int numUpsertSelectRunners = 4;
    ExecutorService exec = Executors.newFixedThreadPool(numUpsertSelectRunners);
    try (Connection conn = driver.connect(url, props)) {
        final UpsertSelectRunner upsertSelectRunner = new UpsertSelectRunner(dataTable, 0, 105, 1);
        // keep running slow upsert selects
        SlowBatchRegionObserver.SLOW_MUTATE = true;
        for (int i = 0; i < numUpsertSelectRunners; i++) {
            exec.submit(new UpsertSelectLooper(upsertSelectRunner));
            Thread.sleep(300);
        }

        final HBaseTestingUtility utility = getUtility();
        // try to close the region while UPSERT SELECTs are happening,
        final HRegionServer dataRs = utility.getHBaseCluster().getRegionServer(0);
        final Admin admin = utility.getAdmin();
        final RegionInfo dataRegion = admin.getRegions(TableName.valueOf(dataTable)).get(0);
        logger.info("Closing data table region");
        admin.unassign(dataRegion.getEncodedNameAsBytes(), true);
        // make sure the region is offline
        utility.waitFor(60000L, 1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                List<RegionInfo> onlineRegions = admin.getRegions(dataRs.getServerName());
                for (RegionInfo onlineRegion : onlineRegions) {
                    if (onlineRegion.equals(dataRegion)) {
                        logger.info("Data region still online");
                        return false;
                    }
                }
                logger.info("Region is no longer online");
                return true;
            }
        });
    } finally {
        SlowBatchRegionObserver.SLOW_MUTATE = false;
        exec.shutdownNow();
        exec.awaitTermination(60, TimeUnit.SECONDS);
    }
}

From source file:org.apache.druid.data.input.impl.prefetch.PrefetchableTextFilesFirehoseFactory.java

@Override
public Firehose connect(StringInputRowParser firehoseParser, @Nullable File temporaryDirectory)
        throws IOException {
    if (objects == null) {
        objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "objects"));
    }//from  ww w. j av a  2s  .  c o m

    if (cacheManager.isEnabled() || prefetchConfig.getMaxFetchCapacityBytes() > 0) {
        Preconditions.checkNotNull(temporaryDirectory, "temporaryDirectory");
        Preconditions.checkArgument(temporaryDirectory.exists(), "temporaryDirectory[%s] does not exist",
                temporaryDirectory);
        Preconditions.checkArgument(temporaryDirectory.isDirectory(),
                "temporaryDirectory[%s] is not a directory", temporaryDirectory);
    }

    LOG.info("Create a new firehose for [%d] objects", objects.size());

    // fetchExecutor is responsible for background data fetching
    final ExecutorService fetchExecutor = Execs.singleThreaded("firehose_fetch_%d");
    final FileFetcher<T> fetcher = new FileFetcher<T>(cacheManager, objects, fetchExecutor, temporaryDirectory,
            prefetchConfig, new ObjectOpenFunction<T>() {
                @Override
                public InputStream open(T object) throws IOException {
                    return openObjectStream(object);
                }

                @Override
                public InputStream open(T object, long start) throws IOException {
                    return openObjectStream(object, start);
                }
            }, getRetryCondition(), getMaxFetchRetry());

    return new FileIteratingFirehose(new Iterator<LineIterator>() {
        @Override
        public boolean hasNext() {
            return fetcher.hasNext();
        }

        @Override
        public LineIterator next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            final OpenedObject<T> openedObject = fetcher.next();
            try {
                return new ResourceCloseableLineIterator(new InputStreamReader(
                        wrapObjectStream(openedObject.getObject(), openedObject.getObjectStream()),
                        StandardCharsets.UTF_8), openedObject.getResourceCloser());
            } catch (IOException e) {
                try {
                    openedObject.getResourceCloser().close();
                } catch (Throwable t) {
                    e.addSuppressed(t);
                }
                throw new RuntimeException(e);
            }
        }
    }, firehoseParser, () -> {
        fetchExecutor.shutdownNow();
        try {
            Preconditions.checkState(
                    fetchExecutor.awaitTermination(prefetchConfig.getFetchTimeout(), TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ISE("Failed to shutdown fetch executor during close");
        }
    });
}

From source file:org.kurento.test.metatest.BrowserCreationTest.java

private void createParallelBrowsers(int numBrowsers) throws InterruptedException {
    long startTime = System.currentTimeMillis();

    final List<Browser> browsers = Collections.synchronizedList(new ArrayList<Browser>());

    ExecutorService executor = Executors.newFixedThreadPool(numBrowsers);

    try {/*from   w w  w  .j a  v  a  2 s  .c  om*/

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (int i = 0; i < numBrowsers; i++) {

            final int numBrowser = i;

            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {

                        Browser browser = new Browser.Builder().scope(BrowserScope.DOCKER).build();

                        browsers.add(browser);

                        browser.setId("browser" + numBrowser);

                        browser.init();

                        latch.countDown();

                    } catch (Throwable t) {
                        latch.abort("Exception setting up test. A browser could not be initialised", t);
                    }
                }
            });
        }

        latch.await();

        long creationTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers started in {} millis", numBrowsers, creationTime);

        log.debug("----------------------------------------------------------------");

    } finally {

        log.debug("***************************************************************");

        startTime = System.currentTimeMillis();

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (final Browser browser : browsers) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    browser.close();
                    latch.countDown();
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.HOURS);

        latch.await();

        long destructionTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers stopped in {} millis", numBrowsers, destructionTime);

        log.debug("----------------------------------------------------------------");
    }
}