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:com.test.test.ClientServerTest.java

@Test
public void testMutliThreaded() throws Exception {

    // Number of threads
    final int size = 10;

    LOG.debug("clientSimple1:" + clientSimple);

    IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
    LOG.debug("proxyService:" + proxyService);

    List<ClientCallable> clientCallableList = new ArrayList<ClientCallable>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallable(proxyService, i));
    }//from www .  ja v a2s .co  m

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallable clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

public void importExternalFontIntoProject(ArrayList<File> externalfiles, ProgressHandler progressHandler) {
    String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/freetypefonts";
    TffFilenameFilter ttfFilenameFilter = new TffFilenameFilter();
    handler = progressHandler;/*w  w  w. j a  va 2  s .c  o  m*/
    float perCopyPercent = 95.0f / externalfiles.size();
    for (File file : externalfiles) {
        if (!ttfFilenameFilter.accept(null, file.getName())) {
            continue;
        }
        try {
            File target = new File(targetPath);
            if (!target.exists()) {
                File newFile = new File(targetPath);
                newFile.mkdir();
            }
            File fileTarget = new File(targetPath + "/" + file.getName());

            FileUtils.copyFile(file, fileTarget);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(perCopyPercent);
        changePercentBy(perCopyPercent);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                changePercentBy(100 - currentPercent);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.progressComplete();
            }
        });
        executor.shutdown();
    }
}

From source file:com.test.test.ClientServerTest.java

@Test
public void testMutliThreadProxyClient() throws Exception {

    // Number of threads
    final int size = 20;

    LOG.debug("clientSimple1:" + clientSimple);

    List<IServiceSimple> serviceSimpleList = new ArrayList<IServiceSimple>();
    for (int i = 0; i < size; i++) {
        IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
        LOG.debug("proxyService:" + proxyService);
        serviceSimpleList.add(proxyService);
    }//from w  w w. j a  va2 s .co  m

    List<ClientCallable> clientCallableList = new ArrayList<ClientCallable>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallable(serviceSimpleList.get(i), i));
    }

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallable clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");

    Thread.sleep(20000);
    LOG.debug("\n\n\n\n+++++++++++++++++++++++++");
    LOG.debug("New system:");
    IServiceSimple proxyService2 = clientSimple.getProxy(IServiceSimple.class);
    proxyService2.functionNumber1("1", "1");

}

From source file:com.clustercontrol.agent.SendQueue.java

/**
 * ????<BR>/*from  www .  ja va  2s.  c o m*/
 * 
 * ?????????<BR>
 * ??????
 * @param msg
 */
public boolean put(Object info) {
    m_log.debug("put() start : " + info.getClass().getCanonicalName());

    while (!ReceiveTopic.isHistoryClear()) {
        m_log.debug("put() while (!ReceiveTopic.isHistoryClear()) is true");

        boolean sendQueueStatus = false;
        ExecutorService es = null;
        Future<Boolean> task = null;
        try {
            String id = "";
            // Executor??
            SenderThreadFactory threadFactory = new SenderThreadFactory(id);
            es = Executors.newSingleThreadExecutor(threadFactory);

            // Queue??
            // ?Queue??????????????????
            // Future.get()????????
            m_log.debug("put() submit");
            task = es.submit(new Sender(info));
            sendQueueStatus = task.get(SEND_TIMEOUT, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            // Queue?????????????Future.get()???????
            // ????

            // ?
            m_log.warn("put() : Failed to connect to MGR " + e.getMessage(), e);

        } finally {
            // 
            if (task != null) {
                task.cancel(true);
            }

            if (es != null) {
                es.shutdown();
            }
            m_log.debug("put() end    : " + info.getClass().getCanonicalName());
        }

        // ??????????sleep????
        // Queue????????
        if (sendQueueStatus) {
            m_log.debug("put() return true : " + info.getClass().getCanonicalName());
            return true;
        } else {
            // sleep???QueueConnection?QueueSession ??
            try {
                m_log.debug("put() reput interval sleep: " + m_sendQueueReconnectionInterval + " sec");
                Thread.sleep(m_sendQueueReconnectionInterval);
            } catch (InterruptedException e1) {
                m_log.error("put() reput interval sleep: ", e1);
            }
        }
    } // End While Loop
    return false;
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importAtlasesIntoProject(final Array<FileHandle> files, ProgressHandler progressHandler) {
    handler = progressHandler;//from   w  ww  . j  a v  a2s  . co m
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        for (FileHandle fileHandle : files) {
            // TODO: logic goes here
        }
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java

protected double computeProbability(String[] gtTaxa, Network speciesNetwork, Map<String, String> allele2species,
        List<Tuple<char[], Integer>> sequences, RateModel rModel, double theta) {
    //long startTime = System.currentTimeMillis();
    double totalProb = 0;
    ExecutorService executor = Executors.newFixedThreadPool(_numThreads);
    List<Future<Double>> futureList = new ArrayList<Future<Double>>();
    int chunkSize = sequences.size() / _numThreads;
    int extraNumber = sequences.size() % _numThreads;
    int extra = 0;
    int startingPoint = 0;
    for (int i = 0; i < _numThreads; i++) {
        int size = extra++ < extraNumber ? chunkSize + 1 : chunkSize;
        MyThread myThread = new MyThread(speciesNetwork.toString(), gtTaxa, allele2species,
                sequences.subList(startingPoint, startingPoint + size), rModel, theta);
        startingPoint += size;//from  w ww  .  j  a v a2s. c om
        Future<Double> future = executor.submit(myThread);
        futureList.add(future);
    }
    for (Future<Double> future : futureList) {
        try {
            totalProb += future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    executor.shutdown();
    //System.out.println((System.currentTimeMillis()-startTime)/1000.0);
    System.out.println(speciesNetwork.toString() + ": " + totalProb);
    return totalProb;
}

From source file:io.siddhi.extension.io.file.FileSourceTextFullModeTestCase.java

@Test
public void siddhiIoFileTest4() throws InterruptedException {
    log.info("test SiddhiIoFile [mode = text.full] 4");
    String streams = "" + "@App:name('TestSiddhiApp')" + "@source(type='file', mode='text.full',"
            + "dir.uri='file:/" + dirUri + "/text_full_single', " + "action.after.process='delete', "
            + "@map(type='json'))" + "define stream FooStream (symbol string, price float, volume long); "
            + "define stream BarStream (symbol string, price float, volume long); ";

    String query = "" + "from FooStream " + "select * " + "insert into BarStream; ";

    SiddhiManager siddhiManager = new SiddhiManager();
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);

    siddhiAppRuntime.addCallback("BarStream", new StreamCallback() {

        @Override//from   w w w . j  a  v a 2 s  . co  m
        public void receive(Event[] events) {
            EventPrinter.print(events);
            int n = count.incrementAndGet();
            for (Event event : events) {
                switch (n) {
                case 1:
                    AssertJUnit.assertEquals("apache", event.getData(0));
                    break;
                case 2:
                    AssertJUnit.assertEquals("google", event.getData(0));
                    break;
                default:
                    AssertJUnit.fail("More events received than expected.");
                }
            }
        }
    });

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            siddhiAppRuntime.start();
        }
    });
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(t1);

    SiddhiTestHelper.waitForEvents(waitTime, 1, count, timeout);

    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            File source = new File(dirUri + "/text_full/google.json");
            File dest = new File(dirUri + "/text_full_single/google.json");
            while (true) {
                if (count.intValue() == 1) {
                    try {
                        FileUtils.copyFile(source, dest);
                        break;
                    } catch (IOException e) {
                        AssertJUnit.fail(
                                "Failed to add a new file to directory '" + dirUri + "/text_full_single'.");
                    }
                }
            }
        }
    });

    executorService.execute(t2);

    SiddhiTestHelper.waitForEvents(waitTime, 2, count, timeout);

    executorService.shutdown();

    File file = new File(dirUri + "/text_full_single");
    AssertJUnit.assertEquals(0, file.list().length);

    //assert event count
    AssertJUnit.assertEquals("Number of events", 2, count.get());
    siddhiAppRuntime.shutdown();
}

From source file:org.pentaho.support.di.server.DISupportUtilityServiceImpl.java

/**
 * loads spring configuration SupportUtil.xml file and creates instance of
 * selected retriever//from   ww  w.  ja v a2s.  c om
 * 
 * @param args
 * @param prop
 * @return
 */
private boolean executeService(String[] args, final Properties prop) {
    Boolean result = false;
    String SPRING_CONFIG_CLASS = "cofingRetrieverFactory";

    try {

        ApplicationContext context = new ClassPathXmlApplicationContext(DIConstant.SPRING_FILE_NAME);
        final CofingRetrieverFactory factory = (CofingRetrieverFactory) context.getBean(SPRING_CONFIG_CLASS);
        ConfigRetreiver[] config = factory.getConfigRetrevier(args);

        ExecutorService service = Executors.newFixedThreadPool(10);

        // loop through created retriever instance and calls respective
        // retriever
        for (final ConfigRetreiver configobj : config) {

            configobj.setDIServerPath(prop);
            configobj.setServerName(selected.getServerName());
            configobj.setInstallType(selected.getInstallType());

            // if retriever instance is FileRetriever, sets required detail
            if (configobj instanceof FileRetriever) {

                configobj.setBidiXml(selected.getBidiXml());
                configobj.setBidiBatFile(selected.getBidiBatFile());
                configobj.setBidiProrperties(selected.getBidiProrperties());
                configobj.setTomcatXml(selected.getTomcatXml());
            }

            // if retriever instance is BrowserInfoRetriever, sets Browser
            // info detail
            if (configobj instanceof BrowserInfoRetriever) {
                configobj.setBrowserInfo(selected.getBrowserInfo());
            }

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

        }

        service.shutdown();
        Thread.sleep(75000);

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

            File file = new File(prop.getProperty(DIConstant.SUPP_INFO_DEST_PATH) + File.separator
                    + prop.getProperty(DIConstant.SUPP_INF_DIR));
            if (file.exists()) {
                // call delete
                delete(file);
            }

            result = true;
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:learn.jersey.services.BufferedMutatorExample.java

@Override
public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

    /** a callback invoked when an asynchronous write fails. */
    final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() {
        @Override/*  w w  w  .java 2  s . c  o  m*/
        public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) {
            for (int i = 0; i < e.getNumExceptions(); i++) {
                LOG.info("Failed to sent put " + e.getRow(i) + ".");
            }
        }
    };
    BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener);

    //
    // step 1: create a single Connection and a BufferedMutator, shared by
    // all worker threads.
    //
    try (final Connection conn = ConnectionFactory.createConnection(getConf());
            final BufferedMutator mutator = conn.getBufferedMutator(params)) {

        /** worker pool that operates on BufferedTable instances */
        final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE);
        List<Future<Void>> futures = new ArrayList<>(TASK_COUNT);

        for (int i = 0; i < TASK_COUNT; i++) {
            futures.add(workerPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    //
                    // step 2: each worker sends edits to the shared
                    // BufferedMutator instance. They all use
                    // the same backing buffer, call-back "listener", and
                    // RPC executor pool.
                    //
                    Put p = new Put(Bytes.toBytes("someRow"));
                    p.addColumn(FAMILY, Bytes.toBytes("someQualifier"), Bytes.toBytes("some value"));
                    mutator.mutate(p);
                    // do work... maybe you want to call mutator.flush()
                    // after many edits to ensure any of
                    // this worker's edits are sent before exiting the
                    // Callable
                    return null;
                }
            }));
        }

        //
        // step 3: clean up the worker pool, shut down.
        //
        for (Future<Void> f : futures) {
            f.get(5, TimeUnit.MINUTES);
        }
        workerPool.shutdown();
    } catch (IOException e) {
        // exception while creating/destroying Connection or BufferedMutator
        LOG.info("exception while creating/destroying Connection or BufferedMutator", e);
    } // BufferedMutator.close() ensures all work is flushed. Could be the
      // custom listener is
      // invoked from here.
    return 0;
}

From source file:com.sm.store.client.ClusterClient.java

/**
 * OpType to determine deserialze payload during merge
 * MultiGets means payload is byte[], else payload is serialized object
 * @param from//from  w w  w.  j  a  v a2 s .  co m
 * @param to
 * @param queryStr
 * @return
 */
public List<KeyValue> scan(Key from, Key to, String queryStr) {
    List<KeyCluster> keyClusterList = findAll();
    OpType opType = (queryStr == null ? OpType.MultiGets : OpType.MultiSelectQuery);
    //return executeRequest( keyClusterList, opType);
    int size = keyClusterList.size();
    List<Key> keyList = new ArrayList<Key>(2);
    keyList.add(from);
    keyList.add(to);
    ScanParaList scanParaList = new ScanParaList(OpType.Get, keyList, queryStr);
    CountDownLatch countDownLatch = new CountDownLatch(size);
    ExecutorService executor = Executors.newFixedThreadPool(size);
    List<Runnable> runnableList = new ArrayList<Runnable>(size);
    for (int i = 0; i < size; i++) {
        Request request = createScanRequest(scanParaList);
        RunThread runThread = new RunThread(request, keyClusterList.get(i), countDownLatch, OpType.Scan);
        runnableList.add(runThread);
        executor.submit(runThread);
    }
    try {
        countDownLatch.await(timeout * 5, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        logger.warn(ex.getMessage(), ex);
    } finally {
        executor.shutdown();
        return mergeResponse(runnableList);
    }
}