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:org.piraso.server.service.ResponseLoggerServiceImplTest.java

@Test
public void testWaitAndStop() throws Exception {
    final AtomicBoolean fail = new AtomicBoolean(false);
    ExecutorService executor = Executors.newFixedThreadPool(2);

    Runnable startServiceRunnable = new Runnable() {
        public void run() {
            try {
                service.start();//  w  ww. jav  a2s  . c o  m
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Runnable logMessagesRunnable = new Runnable() {
        public void run() {
            try {

                service.stopAndWait(3000l);
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Future future = executor.submit(startServiceRunnable);
    executor.submit(logMessagesRunnable);

    future.get();
    executor.shutdown();

    if (fail.get()) {
        fail("failure see exception trace.");
    }

    // no harm invoking it again
    service.stopAndWait(1000l);

    assertFalse(service.isAlive());
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

public void updateCss(final ServletContext context) throws Exception {
    List<Customer> customers = customerDAO.findAll();
    if (customers.isEmpty()) {
        applyCustomerCss(context, getDefaultCssAttributes(), "");
    } else {/*from  w  w  w. j  a v a  2  s  .c o m*/
        lessCompiler = new LessCompiler();
        lessCompiler.init();
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        LOG.info(String.format("Compiling lesscss with %s cores", availableProcessors));
        ExecutorService executor = Executors.newFixedThreadPool(availableProcessors);
        List<FutureTask<Void>> taskList = new ArrayList<>();

        for (final Customer customer : customers) {
            FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        updateCss(context, customer);
                    } catch (Exception ex) {
                        LOG.error(ex, ex);
                    }
                    return null;
                }
            });
            taskList.add(futureTask);
            executor.execute(futureTask);
        }
        for (FutureTask task : taskList) {
            task.get();
        }
        executor.shutdown();
    }
}

From source file:guru.nidi.languager.check.LinkChecker.java

public List<FindResult<String>> findBrokenLinks() {
    ExecutorService executor = Executors.newCachedThreadPool();
    final List<FindResult<String>> res = Collections.synchronizedList(new ArrayList<FindResult<String>>());
    final Set<String> urls = new HashSet<>();
    int lineNum = 1;

    for (MessageLine line : contents.subList(1, contents.size())) {
        lineNum++;//from   ww w .  ja  v  a 2  s.c  o  m
        int col = 1;
        int elemNum = 0;
        for (String element : line) {
            final Matcher matcher = LINK_PATTERN.matcher(element);
            while (matcher.find()) {
                final String url = matcher.group();
                if (!urls.contains(url)) {
                    urls.add(url);
                    executor.submit(new LinkValidator(res, url,
                            new SourcePosition(file, lineNum, col + elemNum + matcher.start())));
                }
            }
            elemNum++;
            col += element.length();
        }
    }
    executor.shutdown();
    try {
        executor.awaitTermination(20, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        //ignore
    }
    return res;
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

public void run(String connectionString) throws Exception {

    CompletableFuture<Void> receiveTask;
    CompletableFuture<Void> fixUpTask;
    IMessageSender sendClient;/*from  ww w.j av a2s . c o  m*/

    sendClient = ClientFactory.createMessageSenderFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"));

    // max delivery-count scenario
    this.sendMessagesAsync(sendClient, 1).join();
    this.exceedMaxDelivery(connectionString, "BasicQueue").join();

    // fix-up scenario
    this.sendMessagesAsync(sendClient, Integer.MAX_VALUE);
    ExecutorService executorService = Executors.newCachedThreadPool();
    receiveTask = this.receiveMessagesAsync(connectionString, "BasicQueue", executorService);
    fixUpTask = this.PickUpAndFixDeadletters(connectionString, "BasicQueue", sendClient, executorService);

    // wait for ENTER or 10 seconds elapsing
    waitForEnter(10);

    receiveTask.cancel(true);
    fixUpTask.cancel(true);

    CompletableFuture.allOf(sendClient.closeAsync(), receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    }), fixUpTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    })).join();

    executorService.shutdown();
}

From source file:c3.ops.priam.resources.BackupServlet.java

/**
 * Convert SSTable2Json and search for given key
 *///www . j  a v  a 2s  . co  m
public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension,
        String jsonFilePath) throws Exception {
    try {
        logger.info("Starting SSTable2Json conversion ...");
        //Setting timeout to 10 Mins
        long TIMEOUT_PERIOD = 10l;
        String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath);

        String[] cmd = { "/bin/sh", "-c", unixCmd.toString() };
        final Process p = Runtime.getRuntime().exec(cmd);

        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int returnCode = p.waitFor();
                return returnCode;
            }
        };

        ExecutorService exeService = Executors.newSingleThreadExecutor();
        try {
            Future<Integer> future = exeService.submit(callable);
            int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES);
            if (returnVal == 0)
                logger.info("Finished SSTable2Json conversion and search.");
            else
                logger.error("Error occurred during SSTable2Json conversion and search.");
        } catch (TimeoutException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw e;
        } finally {
            p.destroy();
            exeService.shutdown();
        }

    } catch (IOException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}

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

protected List<String> createTestClips(FPPool pool, int maxBlobSize, int thisMany, Writer summaryWriter)
        throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(CAS_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   w ww .j a  v  a 2 s .com

    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: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  a  v  a2s  . 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.pentaho.support.cmd.CommandLineUtility.java

/**
 * loads the supportutil.xml file and creates instance of selected retriever
 * and executes/*from  w  w  w. jav a2 s  . c om*/
 * 
 * @param args
 * @param server
 */
private static void executeService(String[] args, String server) {

    final Properties prop = loadSupportProperty();

    // if installation is manual and server is bi-server read web.xml
    if (getInstallationType() == 3 && getServer() == 1) {
        if (prop.getProperty(CMDConstant.BI_TOM_PATH) == null) {
            System.out.println(CMDConstant.ERROR_12);
            System.exit(0);
        } else {

            WEB_XML = new StringBuilder();
            WEB_XML.append(prop.getProperty(CMDConstant.BI_TOM_PATH)).append(File.separator)
                    .append(CMDConstant.WEB_APP).append(File.separator).append(CMDConstant.PENTAHO)
                    .append(File.separator).append(CMDConstant.WEB_INF).append(File.separator)
                    .append(CMDConstant.WEB_XML);

            PENTAHO_SOLU_PATH = getSolutionPath(server, WEB_XML.toString());
            prop.put(CMDConstant.PENTAHO_SOLU_PATH, PENTAHO_SOLU_PATH);
            prop.put(CMDConstant.BI_PATH, PENTAHO_SOLU_PATH);
        }

    } else if (getInstallationType() == 3 && getServer() == 2) {
        // if installation is manual and server is di-server read web.xml
        if (prop.getProperty(CMDConstant.DI_TOM_PATH) == null) {
            System.out.println(CMDConstant.ERROR_22);
            System.exit(0);
        } else {

            WEB_XML = new StringBuilder();
            WEB_XML.append(prop.getProperty(CMDConstant.DI_TOM_PATH)).append(File.separator)
                    .append(CMDConstant.WEB_APP).append(File.separator).append(CMDConstant.PENTAHO_DI)
                    .append(File.separator).append(CMDConstant.WEB_INF).append(File.separator)
                    .append(CMDConstant.WEB_XML);

            PENTAHO_SOLU_PATH = getSolutionPath(server, WEB_XML.toString());
            prop.put(CMDConstant.PENTAHO_SOLU_PATH, PENTAHO_SOLU_PATH);
            prop.put(CMDConstant.BI_PATH, PENTAHO_SOLU_PATH);
        }
    }

    if (getServer() == 1) {

        if (prop.get(CMDConstant.BI_PATH) == null) {

            System.out.println(CMDConstant.ERROR_1);
            System.exit(0);
        }
        if (prop.get(CMDConstant.BI_TOM_PATH) == null) {

            System.out.println(CMDConstant.ERROR_12);
            System.exit(0);
        } else {
            setBIServerPath(prop);
        }

    } else if (getServer() == 2) {
        if (prop.get(CMDConstant.DI_PATH) == null) {
            System.out.println(CMDConstant.ERROR_2);
            System.exit(0);
        }
        if (prop.get(CMDConstant.DI_TOM_PATH) == null) {
            System.out.println(CMDConstant.ERROR_22);
            System.exit(0);
        } else {
            setDIServerPath(prop);
        }
    }

    ApplicationContext context = new ClassPathXmlApplicationContext(CMDConstant.SPRING_FILE_NAME);
    factory = (CofingRetrieverFactory) context.getBean(CMDConstant.COFINGRETRIEVERACTORY);
    ConfigRetreiver[] config = factory.getConfigRetrevier(args);

    ExecutorService service = Executors.newFixedThreadPool(10);
    // loop for all created instance and call respective retriever
    for (final ConfigRetreiver configobj : config) {

        if (getServer() == 1) {

            configobj.setBISeverPath(prop);
            configobj.setServerName("biserver");
        } else if (getServer() == 2) {

            configobj.setDIServerPath(prop);
            configobj.setServerName("diserver");
        }

        if (getInstallationType() == 1) {

            // if installation is installer set Installer
            configobj.setInstallType("Installer");
        } else if (getInstallationType() == 2) {

            // if installation is Archive set Archive
            configobj.setInstallType("Archive");
        } else if (getInstallationType() == 3) {

            // if installation is Manual set Manual
            configobj.setInstallType("Manual");
        }

        // if instance if fileretriever sets required detail
        if (configobj instanceof FileRetriever) {

            configobj.setBidiXml(serverXml);
            configobj.setBidiBatFile(serverBatFile);
            configobj.setBidiProrperties(serverProrperties);
            configobj.setTomcatXml(tomcatXml);
        }

        service.execute(new Runnable() {
            public void run() {
                configobj.readAndSaveConfiguration(prop);
            }
        });

    }

    try {
        service.shutdown();
        Thread.sleep(60000);

        // call for zip
        if (SupportZipUtil.zipFile(prop)) {

            File file = new File(prop.getProperty(CMDConstant.SUPP_INFO_DEST_PATH) + File.separator
                    + prop.getProperty(CMDConstant.SUPP_INF_DIR));
            if (file.exists()) {
                // call for delete empty directory
                delete(file);
                System.exit(0);
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:fi.jumi.launcher.JumiLauncherBuilder.java

public JumiLauncher build() {
    ExecutorService actorsThreadPool = createActorsThreadPool();
    ProcessStarter processStarter = createProcessStarter();
    NetworkServer networkServer = createNetworkServer();
    OutputStream daemonOutputListener = createDaemonOutputListener();

    Actors actors = new MultiThreadedActors(actorsThreadPool, new DynamicEventizerProvider(),
            new PrintStreamFailureLogger(System.out), new NullMessageListener());
    ActorThread actorThread = startActorThread(actors);

    ActorRef<DaemonSummoner> daemonSummoner = actorThread.bindActor(DaemonSummoner.class,
            new ProcessStartingDaemonSummoner(new DirBasedSteward(new EmbeddedDaemonJar()), processStarter,
                    networkServer, daemonOutputListener));
    ActorRef<SuiteLauncher> suiteLauncher = actorThread.bindActor(SuiteLauncher.class,
            new RemoteSuiteLauncher(actorThread, daemonSummoner));

    return new JumiLauncher(suiteLauncher, () -> {
        networkServer.close();/*from  w w  w. j a  v  a 2  s. c  o m*/
        actorThread.stop();
        actorsThreadPool.shutdown();
        try {
            actorsThreadPool.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}

From source file:eu.edisonproject.training.wsd.WikipediaOnline.java

private Map<CharSequence, List<CharSequence>> getCategories(Set<Term> terms)
        throws MalformedURLException, InterruptedException, ExecutionException {
    int maxT = 2;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(maxT);
    ExecutorService pool = new ThreadPoolExecutor(maxT, maxT, 500L, TimeUnit.MICROSECONDS, workQueue);

    //        ExecutorService pool = new ThreadPoolExecutor(maxT, maxT,
    //                5000L, TimeUnit.MILLISECONDS,
    //                new ArrayBlockingQueue<>(maxT, true), new ThreadPoolExecutor.CallerRunsPolicy());
    Map<CharSequence, List<CharSequence>> cats = new HashMap<>();
    Set<Future<Map<CharSequence, List<CharSequence>>>> set = new HashSet<>();
    for (Term t : terms) {
        URL url = new URL(PAGE + "?action=query&format=json&prop=categories&pageids=" + t.getUid());
        LOGGER.log(Level.FINE, url.toString());
        WikiRequestor req = new WikiRequestor(url, t.getUid().toString(), 0);
        Future<Map<CharSequence, List<CharSequence>>> future = pool.submit(req);
        set.add(future);//from   ww  w  .ja  v  a 2 s.co m
    }
    pool.shutdown();

    for (Future<Map<CharSequence, List<CharSequence>>> future : set) {
        while (!future.isDone()) {
            //                LOGGER.log(Level.INFO, "Task is not completed yet....");
            Thread.currentThread().sleep(10);
        }
        Map<CharSequence, List<CharSequence>> c = future.get();
        if (c != null) {
            cats.putAll(c);
        }
    }

    return cats;
}