Example usage for java.util.concurrent ExecutorService shutdownNow

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

Introduction

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

Prototype

List<Runnable> shutdownNow();

Source Link

Document

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Usage

From source file:com.emc.vipr.sync.CasMigrationTest.java

protected List<String> createTestClips(FPPool pool, int maxBlobSize, int thisMany, Writer summaryWriter)
        throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(CAS_SETUP_THREADS);

    System.out.print("Creating clips");

    List<String> clipIds = Collections.synchronizedList(new ArrayList<String>());
    List<String> summaries = Collections.synchronizedList(new ArrayList<String>());
    for (int clipIdx = 0; clipIdx < thisMany; clipIdx++) {
        service.submit(new ClipWriter(pool, clipIds, maxBlobSize, summaries));
    }/*from  ww  w  .j ava2s . c  o m*/

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    Collections.sort(summaries);
    for (String summary : summaries) {
        summaryWriter.append(summary);
    }

    System.out.println();

    return clipIds;
}

From source file:org.apache.hadoop.hive.llap.daemon.impl.TaskExecutorService.java

private void shutdownExecutor(ExecutorService executorService) {
    executorService.shutdown();//from ww w .  j  a v a2s .  c o m
    try {
        if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
            executorService.shutdownNow();
        }
    } catch (InterruptedException e) {
        executorService.shutdownNow();
    }
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Uploads the given recipe to the server.
 * @param recipe The recipe to be uploaded.
 * ReturnCode.ERROR if anything goes wrong, ReturnCode.ALREADY_EXISTS if a recipe
 * by that name already exists on the server (this will eventually be modified to check
 * against URI instead of Recipe title), ReturnCode.SUCCESS if the recipe was successfully
 * uploaded, or ReturnCode.BUSY if the network is not responding or the operation is 
 * taking too long.// w  w w  . j a v  a 2s.  c  om
 */
public ReturnCode uploadRecipe(Recipe recipe) throws IllegalStateException, IOException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new UploadRecipeTask(recipe));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Upload Recipe operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during upload recipe operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.AWSCloudTrailProcessingExecutor.java

/**
 * Helper function to gracefully stop an {@link ExecutorService}.
 *
 * @param threadPool the thread pool to stop.
 *///from  w  ww .  ja v  a 2  s.  co m
private void stopThreadPool(ExecutorService threadPool) {
    LibraryUtils.checkCondition(threadPool == null, "Thread pool is null when calling stop");

    if (threadPool.isShutdown()) {
        logger.debug(threadPool.toString() + " is already stopped.");

    } else {

        logger.debug(threadPool.toString() + " is about to shutdown.");
        threadPool.shutdown(); // Shutdown thread pool

        try { // Wait for shutdown
            threadPool.awaitTermination(this.config.getThreadTerminationDelaySeconds(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.debug("Wait thread pool termination is interrupted.");
        }

        if (!threadPool.isShutdown()) { // ShutdownNow after waiting
            logger.debug(threadPool.toString() + " is force to shutdown now.");
            threadPool.shutdownNow();
        }

        logger.debug(threadPool.toString() + " is stopped.");
    }
}

From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java

private void shutDownExecutorService(ExecutorService executorService) throws InterruptedException {
    executorService.shutdownNow();
    if (!executorService.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
        //If it cant be stopped then throw exception
        throw new RuntimeException("Could not shutdown Executor service");
    }/*  www.  j a  v a  2 s  .c om*/
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Performs a search of online recipes by keywords.
 * @param str The string of keywords we wish to search by.
 * @return ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if
 * the search returned no results, ReturnCode.SUCCESS if the search was successful,
 * in which case the results are written to the database and the observing views
 * are notified, ReturnCode.BUSY if the server was busy or the operation took
 * longer than TIME_PERIOD seconds./* ww  w  .  j  a v  a2  s  .c o m*/
 */
public ReturnCode searchByKeywords(String str) throws ClientProtocolException, IOException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new SearchByKeywordsTask(str));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Search by Keywords operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during Search by Keywords operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpStreamResponse executeStreamWithTimeout(final HttpMethodBase HttpMethod, int timeoutMillis) {
    client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
    ExecutorService service = Executors.newSingleThreadExecutor();

    Future<HttpStreamResponse> future = service.submit(new Callable<HttpStreamResponse>() {
        @Override/* w  w w . j av  a  2s  .  com*/
        public HttpStreamResponse call() throws IOException {
            return executeStream(HttpMethod);
        }
    });

    try {
        return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        String uriInfo = "";
        try {
            uriInfo = " for " + HttpMethod.getURI();
        } catch (Exception ie) {
        }
        LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e);
        return null;
    } finally {
        service.shutdownNow();
    }
}

From source file:org.apache.hadoop.hbase.util.RegionMover.java

/**
 * Loads the specified {@link #hostname} with regions listed in the {@link #filename} RegionMover
 * Object has to be created using {@link #RegionMover(RegionMoverBuilder)}
 * @return true if loading succeeded, false otherwise
 * @throws ExecutionException/*from  w  ww  .  j  a  v a 2 s  . c  o  m*/
 * @throws InterruptedException if the loader thread was interrupted
 * @throws TimeoutException
 */
public boolean load() throws ExecutionException, InterruptedException, TimeoutException {
    setConf();
    ExecutorService loadPool = Executors.newFixedThreadPool(1);
    Future<Boolean> loadTask = loadPool.submit(new Load(this));
    loadPool.shutdown();
    try {
        if (!loadPool.awaitTermination((long) this.timeout, TimeUnit.SECONDS)) {
            LOG.warn("Timed out before finishing the loading operation. Timeout:" + this.timeout + "sec");
            loadPool.shutdownNow();
        }
    } catch (InterruptedException e) {
        loadPool.shutdownNow();
        Thread.currentThread().interrupt();
    }
    try {
        return loadTask.get(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while loading Regions on " + this.hostname, e);
        throw e;
    } catch (ExecutionException e) {
        LOG.error("Error while loading regions on RegionServer " + this.hostname, e);
        throw e;
    }
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Query the server for Recipes which contains at subset of the given ingredients list.
 * @param ingredients The list of ingredients by which to search.
 * @return  ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if
 * the search returned no results, ReturnCode.SUCCESS if the search was successful,
 * in which case the results are written to the database and the observing views
 * are notified, ReturnCode.BUSY if the server was busy or the operation took
 * longer than TIME_PERIOD seconds.//from w  ww.j  a va2  s.  co  m
 */
public ReturnCode searchByIngredients(ArrayList<Ingredient> ingredients) {

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new SearchByIngredientsTask(ingredients));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Search by Ingredients operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during Search by Ingredients operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Upload the given Photo to the appropriate Recipe.
 * @param (Photo) photo The photo to be added to the server-side version of the Recipe.
 * @param (long) uri The uri of the Recipe to be updated.
 * @return NOT_FOUND if the Recipe cannot be found on the server,
 *          ERROR on any other error occurred while attempting to upload,
 *          SUCCESS on successful upload.
 *//*from   www  .  ja  va2 s .co m*/
public ReturnCode uploadPhotoToRecipe(Photo photo, long uri) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new UploadPhotoTask(photo, uri));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD + UPLOAD_PHOTO_GRACE_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Upload photo operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during upload photo operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}