Example usage for java.util.concurrent ExecutorService shutdown

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

Introduction

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

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:eu.artofcoding.beetlejuice.spring.SpringContextHelper.java

/**
 * http://forum.springsource.org/showthread.php?125695-Orderly-shutdown-how-to-know-when-downstream-executor-is-idle
 * @param shutdownForced/*from  www . j  a  va2s . com*/
 */
public void stopSchedulers(boolean shutdownForced) {
    logger.info(String.format("Stopping schedulers %s", shutdownForced ? "(force)" : ""));
    List<ExecutorService> executorServices = new ArrayList<ExecutorService>();
    Map<String, ThreadPoolTaskScheduler> schedulers = applicationContext
            .getBeansOfType(ThreadPoolTaskScheduler.class);
    for (Map.Entry<String, ThreadPoolTaskScheduler> entry : schedulers.entrySet()) {
        ThreadPoolTaskScheduler scheduler = entry.getValue();
        logger.info(String.format("Stopping scheduler %s", scheduler.getThreadNamePrefix()));
        ExecutorService executorService = scheduler.getScheduledExecutor();
        executorServices.add(executorService);
        if (shutdownForced) {
            executorService.shutdownNow();
        } else {
            executorService.shutdown();
        }
    }
    waitForExecutors(executorServices);
    logger.info("Stopped schedulers");
}

From source file:eu.cloudscale.showcase.servlets.helpers.PaymentService.java

@Async
public Future<String> callPaymentService(String distribution, String attr1, String attr2, String attr3) {
    try {//from   www .jav  a 2  s. com
        ExecutorService executor = Executors.newFixedThreadPool(1);
        String url = this.getUrl(distribution, attr1, attr2, attr3);
        Future<Response> response = executor.submit(new Request(new URL(url)));
        InputStream input = response.get().getBody();
        executor.shutdown();

        String body = IOUtils.toString(input, "UTF-8");
        return new AsyncResult<String>(body);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.janrain.backplane2.server.config.Backplane2Config.java

@PreDestroy
private void cleanup() {
    Metrics.shutdown();//from  w w w.  j  a  v  a2 s  .  co  m

    for (ExecutorService executor : backgroundServices) {
        try {
            executor.shutdown();
            if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
                logger.info("Background thread shutdown properly");
            } else {
                executor.shutdownNow();
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    logger.error("Background thread did not terminate");
                }
            }
        } catch (InterruptedException e) {
            logger.error("error shutting down background service", e);
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.SubmittedJob.java

public void submit() {
    ExecutorService async = Executors.newSingleThreadExecutor();
    runningJob = async.submit(this);
    async.shutdown();
}

From source file:cn.vko.cache.dao.ha.FailoverHotSwapDataSourceCreator.java

private void shutdownExecutor(ExecutorService executor) {
    try {/*w w  w.j av a2s .  com*/
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (Exception ex) {
        logger.warn("interrupted when shutting down executor service.");
    }
}

From source file:net.openhft.chronicle.logger.slf4j.Slf4jIndexedChronicleBinaryLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-binary-indexed-chronicle"));

    final int RUNS = 1000000;
    final int THREADS = 10;

    for (int size : new int[] { 64, 128, 256 }) {
        final long start = System.nanoTime();

        ExecutorService es = Executors.newFixedThreadPool(THREADS);
        for (int t = 0; t < THREADS; t++) {
            es.submit(new RunnableLogger(RUNS, size, "perf-binary-indexed-chronicle"));
        }/*from ww  w  .  j a  v a2 s. co  m*/

        es.shutdown();
        es.awaitTermination(30, TimeUnit.SECONDS);

        final long time = System.nanoTime() - start;

        System.out.printf(
                "ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n",
                RUNS, size, time / 1e6, time / 1e3 / (RUNS * THREADS));
    }

    ChronicleTools.deleteOnExit(basePath("perf-binary-indexed-chronicle"));
}

From source file:FullReindexer.java

public void reindex() throws IOException {
    ExecutorService executor = Executors.newFixedThreadPool(totalThreads);

    for (int i = 0; i < totalThreads; i++) {
        Worker worker = new Worker(i, totalThreads, readClient, writeClient);
        executor.execute(worker);/*  ww w .j av a 2  s. c  o  m*/
    }

    executor.shutdown();

    while (!executor.isTerminated()) {
        // Wait until done
    }

    readClient.close();
    writeClient.close();
}

From source file:org.yamj.core.service.ArtworkProcessScheduler.java

@Scheduled(initialDelay = 30000, fixedDelay = 60000)
public void processArtwork() throws Exception {
    int maxThreads = configService.getIntProperty("yamj3.scheduler.artworkprocess.maxThreads", 1);
    if (maxThreads <= 0) {
        if (!messageDisabled) {
            messageDisabled = Boolean.TRUE;
            LOG.info("Artwork processing is disabled");
        }/* w  ww . ja  v  a2  s  .co m*/
        return;
    } else {
        messageDisabled = Boolean.FALSE;
    }

    int maxResults = configService.getIntProperty("yamj3.scheduler.artworkprocess.maxResults", 20);
    List<QueueDTO> queueElements = artworkStorageService.getArtworLocatedQueue(maxResults);
    if (CollectionUtils.isEmpty(queueElements)) {
        LOG.debug("No artwork found to process");
        return;
    }

    LOG.info("Found {} artwork objects to process; process with {} threads", queueElements.size(), maxThreads);
    BlockingQueue<QueueDTO> queue = new LinkedBlockingQueue<QueueDTO>(queueElements);

    ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
    for (int i = 0; i < maxThreads; i++) {
        ArtworkProcessRunner worker = new ArtworkProcessRunner(queue, artworkProcessorService);
        executor.execute(worker);
    }
    executor.shutdown();

    // run until all workers have finished
    while (!executor.isTerminated()) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException ignore) {
        }
    }

    LOG.debug("Finished artwork processing");
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibMatrixDatagen.java

/**
 * Function to generate a matrix of random numbers. This is invoked both
 * from CP as well as from MR. In case of CP, it generates an entire matrix
 * block-by-block. A <code>bigrand</code> is passed so that block-level
 * seeds are generated internally. In case of MR, it generates a single
 * block for given block-level seed <code>bSeed</code>.
 * /*from   ww w.j  a va 2  s . c o  m*/
 * When pdf="uniform", cell values are drawn from uniform distribution in
 * range <code>[min,max]</code>.
 * 
 * When pdf="normal", cell values are drawn from standard normal
 * distribution N(0,1). The range of generated values will always be
 * (-Inf,+Inf).
 * 
 * @param rows
 * @param cols
 * @param rowsInBlock
 * @param colsInBlock
 * @param sparsity
 * @param min
 * @param max
 * @param bigrand
 * @param bSeed
 * @return
 * @throws DMLRuntimeException
 */
public static void generateRandomMatrix(MatrixBlock out, RandomMatrixGenerator rgen, long[] nnzInBlocks,
        Well1024a bigrand, long bSeed, int k) throws DMLRuntimeException {
    int rows = rgen._rows;
    int cols = rgen._cols;
    int rpb = rgen._rowsPerBlock;
    int cpb = rgen._colsPerBlock;
    double sparsity = rgen._sparsity;

    if (rows == 1) {
        generateRandomMatrix(out, rgen, nnzInBlocks, bigrand, bSeed);
        return;
    }

    boolean invokedFromCP = true;
    if (bigrand == null && nnzInBlocks != null)
        invokedFromCP = false;

    // sanity check valid dimensions and sparsity
    checkMatrixDimensionsAndSparsity(rows, cols, sparsity);

    /*
     * Setup min and max for distributions other than "uniform". Min and Max
     * are set up in such a way that the usual logic of
     * (max-min)*prng.nextDouble() is still valid. This is done primarily to
     * share the same code across different distributions.
     */
    double min = 0, max = 1;
    if (rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)) {
        min = rgen._min;
        max = rgen._max;
    }

    // Determine the sparsity of output matrix
    // if invoked from CP: estimated NNZ is for entire matrix (nnz=0, if 0 initialized)
    // if invoked from MR: estimated NNZ is for one block
    final long estnnz = (invokedFromCP ? ((min == 0.0 && max == 0.0) ? 0 : (long) (sparsity * rows * cols))
            : nnzInBlocks[0]);
    boolean lsparse = MatrixBlock.evalSparseFormatInMemory(rows, cols, estnnz);
    out.reset(rows, cols, lsparse);

    // Special case shortcuts for efficiency
    if (rgen._pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)) {
        //specific cases for efficiency
        if (min == 0.0 && max == 0.0) { //all zeros
            // nothing to do here
            out.nonZeros = 0;
            return;
        } else if (!out.sparse && sparsity == 1.0d && min == max) //equal values
        {
            out.init(min, out.rlen, out.clen);
            return;
        }
    }

    // Allocate memory
    if (out.sparse) {
        //note: individual sparse rows are allocated on demand,
        //for consistency with memory estimates and prevent OOMs.
        out.allocateSparseRowsBlock();
    } else {
        out.allocateDenseBlock();
    }

    int nrb = (int) Math.ceil((double) rows / rpb);
    int ncb = (int) Math.ceil((double) cols / cpb);

    try {
        ExecutorService pool = Executors.newFixedThreadPool(k);
        ArrayList<RandTask> tasks = new ArrayList<RandTask>();
        int blklen = ((int) (Math.ceil((double) nrb / k)));
        for (int i = 0; i < k & i * blklen < nrb; i++) {
            long[] seeds = generateSeedsForCP(bigrand, blklen, ncb);
            tasks.add(new RandTask(invokedFromCP, i * blklen, Math.min((i + 1) * blklen, nrb), out, rgen,
                    nnzInBlocks, bSeed, seeds));
        }
        pool.invokeAll(tasks);
        pool.shutdown();

        //early error notify in case not all tasks successful
        for (RandTask rt : tasks)
            if (!rt.getReturnCode())
                throw new DMLRuntimeException("RandGen task failed: " + rt.getErrMsg());
    } catch (Exception e) {
        throw new DMLRuntimeException(e);
    }

    out.recomputeNonZeros();
}

From source file:com.baifendian.swordfish.execserver.runner.flow.FlowRunnerManager.java

/**
 *  executor service/*from w w  w .j av  a  2s . c o  m*/
 */
private void shutdownExecutorService(ExecutorService executorService, boolean shutdownNow) {
    if (!executorService.isShutdown()) {
        try {
            if (!shutdownNow) {
                executorService.shutdown();
            } else {
                executorService.shutdownNow();
            }

            executorService.awaitTermination(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}