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:example.rhino.DynamicScopesWithHandlebars.java

private static void runScripts(Context cx, Script script, ExecutorService executor) {
    ScriptableObject sharedScope = cx.initStandardObjects(null, true);
    script.exec(cx, sharedScope);//from  ww  w  .j a va 2  s .c  o  m

    Runnable[] run = new Runnable[NUM_THREAD];
    for (int i = 0; i < NUM_THREAD; i++) {

        String source2 = "Handlebars.precompile(template)";

        run[i] = new PerThread(sharedScope, source2, i);
    }
    for (int i = 0; i < NUM_THREAD; i++) {
        executor.execute(run[i]);
    }

    executor.shutdown();

    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java

public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception {

    JanusGraphManagement mgmt = graph.openManagement();
    if (mgmt.getGraphIndex(CHARACTER) == null) {
        final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
        mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
    }//from  w  w w  .j av a 2 s  . c  om
    if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
        final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
        mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
        mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
        mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
    }
    mgmt.commit();

    ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/marvel.csv");
    int line = 0;
    Map<String, Set<String>> comicToCharacter = new HashMap<>();
    Map<String, Set<String>> characterToComic = new HashMap<>();
    Set<String> characters = new HashSet<>();
    BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
    try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null && line < rowsToLoad) {
            line++;
            String comicBook = nextLine[1];
            String[] characterNames = nextLine[0].split("/");
            if (!comicToCharacter.containsKey(comicBook)) {
                comicToCharacter.put(comicBook, new HashSet<String>());
            }
            List<String> comicCharacters = Arrays.asList(characterNames);
            comicToCharacter.get(comicBook).addAll(comicCharacters);
            characters.addAll(comicCharacters);

        }
    }

    for (String character : characters) {
        creationQueue.add(new CharacterCreationCommand(character, graph));
    }

    BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
    for (String comicBook : comicToCharacter.keySet()) {
        creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
        Set<String> comicCharacters = comicToCharacter.get(comicBook);
        for (String character : comicCharacters) {
            AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
            appearedQueue.add(lineCommand);
            if (!characterToComic.containsKey(character)) {
                characterToComic.put(character, new HashSet<String>());
            }
            characterToComic.get(character).add(comicBook);
        }
        REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
    }

    int maxAppearances = 0;
    String maxCharacter = "";
    for (String character : characterToComic.keySet()) {
        Set<String> comicBookSet = characterToComic.get(character);
        int numberOfAppearances = comicBookSet.size();
        REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
        if (numberOfAppearances > maxAppearances) {
            maxCharacter = character;
            maxAppearances = numberOfAppearances;
        }
    }
    LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);

    ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i = 0; i < POOL_SIZE; i++) {
        executor.execute(new BatchCommand(graph, creationQueue));
    }
    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + creationQueue.size());
        if (report) {
            REPORTER.report();
        }
    }

    executor = Executors.newSingleThreadExecutor();
    executor.execute(new BatchCommand(graph, appearedQueue));

    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + appearedQueue.size());
        if (report) {
            REPORTER.report();
        }
    }
    LOG.info("MarvelGraphFactory.load complete");
}

From source file:io.cloudslang.content.azure.services.AuthorizationTokenImpl.java

@NotNull
public static AuthenticationResult getToken(@NotNull final AuthorizationTokenInputs inputs) throws Exception {
    final ExecutorService service = Executors.newSingleThreadExecutor();
    final AuthenticationContext context = new AuthenticationContext(inputs.getAuthority(), false, service);
    context.setProxy(getProxy(inputs.getProxyHost(), inputs.getProxyPort(), inputs.getProxyUsername(),
            inputs.getProxyPassword()));
    final Future<AuthenticationResult> future = context.acquireToken(inputs.getResource(), inputs.getClientId(),
            inputs.getUsername(), inputs.getPassword(), null);
    service.shutdown();
    return future.get();
}

From source file:Main.java

public static Set<String> findMatches(List<String> searchList, Set<String> targetSet)
        throws InterruptedException, ExecutionException {
    Set<String> locatedMatchSet = new HashSet<String>();

    int threadCount = Runtime.getRuntime().availableProcessors();
    List<List<String>> partitionList = getChunkList(searchList, threadCount);

    if (partitionList.size() == 1) {
        // if we only have one "chunk" then don't bother with a thread-pool
        locatedMatchSet = new ListSearcher(searchList, targetSet).call();
    } else {/*w  w  w  .  j av a 2  s  .co  m*/
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        CompletionService<Set<String>> completionService = new ExecutorCompletionService<Set<String>>(executor);
        for (List<String> chunkList : partitionList)
            completionService.submit(new ListSearcher(chunkList, targetSet));

        for (int x = 0; x < partitionList.size(); x++) {
            Set<String> threadMatchSet = completionService.take().get();
            locatedMatchSet.addAll(threadMatchSet);
        }
        executor.shutdown();
    }
    return locatedMatchSet;
}

From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java

public static void executeJobs() throws ServiceException, Exception {
    List<ExpressionJobObj> jobObjList = getExpressionJobs();
    if (jobObjList == null || jobObjList.size() < 1) {
        return;//from w w w. ja  v  a2  s.c om
    }
    ExecutorService exprJobPool = Executors
            .newFixedThreadPool(SimpleUtils.getAvailableProcessors(jobObjList.size()));
    for (ExpressionJobObj jobObj : jobObjList) {
        jobObj = exprJobPool.submit(new ExpressionJobExecuteCallable(jobObj)).get();
    }
    exprJobPool.shutdown();
}

From source file:com.microsoft.azure.storage.util.KVCredentials.java

/**
 * Creates the access token/*from  w w w .java2 s .com*/
 * 
 * @param authorization
 *            The authorization from the service
 * @param resource
 *            The resource being accessed
 * @param clientId
 *            The ClientID for this application
 * @param clientKey
 *            The Client Secret for this application
 * @return The access token to use to authenticate to the service
 */
private static AuthenticationResult getAccessTokenFromClientCredentials(String authorization, String resource,
        String clientId, String clientKey) {
    AuthenticationContext context = null;
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        context = new AuthenticationContext(authorization, false, service);
        ClientCredential credentials = new ClientCredential(clientId, clientKey);
        Future<AuthenticationResult> future = context.acquireToken(resource, credentials, null);
        result = future.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        service.shutdown();
    }

    if (result == null) {
        throw new RuntimeException("authentication result was null");
    }
    return result;
}

From source file:com.uniteddev.Unity.Downloader.java

public static void removeRedundancies() throws InterruptedException {
    class removeRedundancy implements Runnable {
        private int i;

        removeRedundancy(int i) {
            this.i = i;
        }/*from w  ww.  j a va2 s  . c o m*/

        public void run() {
            files.remove(this.i);
        }
    }

    int i = 0;
    ExecutorService pool = Executors.newFixedThreadPool(cores);
    while (i < files.size()) {
        String file = files.get(i);
        file = namefix(file);
        if (new File(Minecraft.getWorkingDirectory(), file).exists())
            pool.submit(new removeRedundancy(i)); // this was originally a while loop
        else
            i++;
    }
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ??/*from   w  w w .ja  v a2 s  . co  m*/
 */
private static void initDbData(final MyTvData data) {
    final TvService tvService = new TvServiceImpl();
    makeCache(tvService);

    // ??
    ExecutorService executorService = Executors.newSingleThreadExecutor(
            new BasicThreadFactory.Builder().namingPattern("Mytv_Crawl_Task_%d").build());
    executorService.execute(new Runnable() {

        @Override
        public void run() {
            runCrawlTask(data, tvService);
        }
    });
    executorService.shutdown();
    // ??
    logger.info("create everyday crawl task.");
    createEverydayCron(data, tvService);
}

From source file:com.antsdb.saltedfish.util.UberUtil.java

public static <T> List<T> runParallel(int nThreads, Callable<T> callback) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(nThreads);
    List<Future<T>> futures = new ArrayList<>();
    for (int i = 0; i < nThreads; i++) {
        Callable<T> run = (Callable<T>) UberUtil.clone(callback);
        futures.add(pool.submit(run));/*from ww w  .  j a v a 2  s  .  c  o m*/
    }
    List<T> result = new ArrayList<>();
    for (Future<T> i : futures) {
        result.add(i.get());
    }
    pool.shutdown();
    return result;
}

From source file:edu.stanford.epad.epadws.queries.Dcm4CheeQueries.java

public static DICOMElementList getDICOMElementsFromWADO(String studyUID, String seriesUID, String imageUID,
        SegmentedProperty catTypeProp) {
    String catCode = "";
    String typeCode = "";
    DICOMElementList dicomElementList = new DICOMElementList();
    DICOMElementList dicomElementListNoSkip = new DICOMElementList();
    boolean skipThumbnail = false;
    try {//from w ww  .  j av a 2  s  . c om
        File temporaryDICOMFile = File.createTempFile(imageUID, ".tmp");
        int wadoStatusCode = DCM4CHEEUtil.downloadDICOMFileFromWADO(studyUID, seriesUID, imageUID,
                temporaryDICOMFile);
        if (wadoStatusCode == HttpServletResponse.SC_OK) {
            File tempTag = File.createTempFile(imageUID, "_tag.tmp");
            ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
            taskExecutor.execute(new DicomHeadersTask(seriesUID, temporaryDICOMFile, tempTag));
            taskExecutor.shutdown();
            try {
                taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                BufferedReader tagReader = null;
                try {
                    String dicomElementString;
                    FileReader tagFileReader = new FileReader(tempTag.getAbsolutePath());
                    tagReader = new BufferedReader(tagFileReader);
                    skipThumbnail = false;
                    String currentSequence = "";
                    while ((dicomElementString = tagReader.readLine()) != null) {

                        if (dicomElementString.contains("(0009,1110)")) // hard code for now TODO:???
                            skipThumbnail = true;
                        if (dicomElementString.contains("(FFFE,E0DD)"))
                            skipThumbnail = false;
                        int sequence = dicomElementString.indexOf("SQ #-1");
                        if (sequence != -1)
                            currentSequence = dicomElementString.substring(sequence + 7);
                        if (dicomElementString.contains("Sequence Delimitation Item"))
                            currentSequence = "";
                        DICOMElement dicomElement = decodeDICOMElementString(dicomElementString);
                        DICOMElement dicomElementNoSkip = decodeDICOMElementString(dicomElementString);
                        if (dicomElement != null) {
                            if (!skipThumbnail) {
                                dicomElement.parentSequenceName = currentSequence;
                                dicomElementList.addDICOMElement(dicomElement);
                                if (dicomElementString.contains("(0008,0100)")) {
                                    if (dicomElement.parentSequenceName != null
                                            && dicomElement.parentSequenceName.equalsIgnoreCase(
                                                    "Segmented Property Category Code Sequence"))//category code
                                    {
                                        catCode = dicomElement.value.trim();
                                        log.info("cat code is " + catCode);
                                    } else if (dicomElement.parentSequenceName != null
                                            && dicomElement.parentSequenceName
                                                    .equalsIgnoreCase("Segmented Property Type Code Sequence"))//category code
                                    {
                                        typeCode = dicomElement.value.trim();
                                        log.info("type code is " + typeCode);
                                    }
                                }
                            }
                            //make a list with all the skip items
                            //at the end if the skip is not closed then use this list
                            else {
                                log.warning("Warning: skip sequence. skipping " + dicomElementString);
                                dicomElementNoSkip.parentSequenceName = currentSequence;
                                dicomElementListNoSkip.addDICOMElement(dicomElementNoSkip);
                            }
                        } else {
                            //too much log
                            //                         log.warning("Warning: could not decode DICOM element " + dicomElementString + "");
                        }
                    }
                } finally {
                    IOUtils.closeQuietly(tagReader);
                    try {
                        temporaryDICOMFile.delete();
                        tempTag.delete();
                    } catch (Exception x) {
                    }
                    ;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warning("DICOM headers task for series " + seriesUID + " interrupted!");
            }
        } else {
            log.warning("Error invoking dcm4chee to get DICOM headers for series " + seriesUID
                    + "; status code=" + wadoStatusCode);
        }
    } catch (IOException e) {
        log.warning("IOException retrieving DICOM headers for image " + imageUID + " in series " + seriesUID,
                e);
    }
    try {
        if (catTypeProp != null && !catCode.equals("") && !typeCode.equals("")) {
            SegmentedPropertyHelper helper = new SegmentedPropertyHelper();
            SegmentedProperty prop = helper.getProperty(catCode, typeCode);
            if (prop != null) {
                catTypeProp.copyValuesFrom(prop);
            } else {
                log.info("Category-type pair not found");
            }
        }
    } catch (Exception ex) {
        log.warning("Exception in getting category type ", ex);
    }

    if (skipThumbnail) {
        log.warning("End of skip not found returning noskip data. ");
        return dicomElementListNoSkip;
    }
    return dicomElementList;
}