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.uwsoft.editor.proxy.ProjectManager.java

public void importFontIntoProject(Array<FileHandle> fileHandles, ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;/* w  w  w  . j  av  a  2  s .  co  m*/
    }
    String targetPath = currentProjectPath + "/assets/orig/freetypefonts";
    handler = progressHandler;
    float perCopyPercent = 95.0f / fileHandles.size;
    for (FileHandle fileHandle : fileHandles) {
        if (!Overlap2DUtils.TTF_FILTER.accept(null, fileHandle.name())) {
            continue;
        }
        try {
            File target = new File(targetPath);
            if (!target.exists()) {
                File newFile = new File(targetPath);
                newFile.mkdir();
            }
            File fileTarget = new File(targetPath + "/" + fileHandle.name());
            FileUtils.copyFile(fileHandle.file(), fileTarget);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(perCopyPercent);
        changePercentBy(perCopyPercent);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            changePercentBy(100 - currentPercent);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.progressComplete();
        });
        executor.shutdown();
    }
}

From source file:com.wavemaker.tools.apidocs.tools.spring.SpringSwaggerParserTest.java

@Test
public void testMultiThread2() throws InterruptedException {
    ExecutorService service = Executors.newFixedThreadPool(4);
    final Class<VacationController> controllerClass = VacationController.class;

    for (int i = 0; i < 10; i++) {
        final int finalI = i;
        service.execute(new Runnable() {
            public void run() {
                Swagger swagger;// w  w  w .ja v  a2 s  .c  o m
                try {
                    swagger = runForSingleClass(controllerClass);
                } catch (SwaggerParserException e) {
                    throw new RuntimeException("Exception while parsing class:" + controllerClass.getName(), e);
                }
                Assert.assertNotNull(swagger);
                assertEquals(1, swagger.getTags().size());
                assertEquals(controllerClass.getName(), swagger.getTags().get(0).getFullyQualifiedName());
                try {
                    writeToFile(swagger,
                            "mul_class" + controllerClass.getSimpleName() + "_" + finalI + ".json");
                } catch (IOException e) {
                    throw new RuntimeException("Error while writing to file", e);
                }
            }
        });
    }

    service.shutdown();
    service.awaitTermination(10, TimeUnit.SECONDS);
}

From source file:org.pentaho.support.bi.server.BISupportUtilityServiceImpl.java

/**
 * loads spring configuration SupportUtil.xml file and creates instance of
 * selected retriever//from   www . j a va 2 s.  com
 * 
 * @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(BIConstant.SPRING_FILE_NAME);
        final CofingRetrieverFactory factory = (CofingRetrieverFactory) context.getBean(SPRING_CONFIG_CLASS);
        ConfigRetreiver[] config = factory.getConfigRetrevier(args);

        ExecutorService service = Executors.newFixedThreadPool(10);

        // based on the instance created respective retriever is called
        for (final ConfigRetreiver configobj : config) {

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

            // if file retriever instance set required detail
            if (configobj instanceof FileRetriever) {

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

            // if browser retriever instance set required detail
            if (configobj instanceof BrowserInfoRetriever) {
                configobj.setBrowserInfo(selected.getBrowserInfo());
            }

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

        }

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

        // calls ziputility for zip
        if (SupportZipUtil.zipFile(prop)) {

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

            result = true;
        }

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

    return result;
}

From source file:de.tudarmstadt.lt.seg.app.Segmenter.java

private void run_parallel() throws Exception {

    InputStream in = System.in;
    if (!"-".equals(_filename_in))
        in = new FileInputStream(_filename_in);
    Stream<String> liter = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset())).lines();

    ThreadLocal<ISentenceSplitter> sentenceSplitter = ThreadLocal.withInitial(() -> {
        try {/*from  w  w  w . j  a  v  a  2 s .  co m*/
            return newSentenceSplitter();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    });
    ThreadLocal<ITokenizer> tokenizer = ThreadLocal.withInitial(() -> {
        try {
            return newTokenizer();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    });

    final PrintWriter[] w = new PrintWriter[_parallelism];
    // init writers
    for (int i = 0; i < _parallelism; i++) {
        OutputStream out = System.out;
        if (!"-".equals(_filename_out)) {
            out = new FileOutputStream(String.format("%s_%d", _filename_out, i));
        }
        w[i] = new PrintWriter(new OutputStreamWriter(out, Charset.defaultCharset()));
    }

    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(_parallelism * 2, true);
    ExecutorService es = new ThreadPoolExecutor(_parallelism, _parallelism, 0L, TimeUnit.MILLISECONDS, queue);

    AtomicLong lc = new AtomicLong(0);
    liter.forEach((line) -> {
        // don't try to submit new threads, wait until the thread queue has some capacity again
        while (queue.remainingCapacity() == 0)
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                /**/}
        es.submit(() -> {
            final long docid = lc.incrementAndGet();
            if (docid % 1000 == 0)
                System.err.format("Processing line %d ('%s')%n", docid, _filename_in);
            final int w_i = (int) (docid % _parallelism);
            split_and_tokenize(new StringReader(line.trim()), String.format("%s:%d", _filename_in, docid),
                    sentenceSplitter.get(), tokenizer.get(), _level_filter, _level_normalize, _merge_types,
                    _merge_tokens, _separator_sentence, _separator_token, _separator_desc, w[w_i]);

        });
    });
    es.shutdown();
    es.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);

    // TODO: the stream parallelism version does not work because it submits too many threads at once
    //      AtomicLong lc = new AtomicLong(0);
    //      ForkJoinPool forkJoinPool = new ForkJoinPool(_parallelism);
    //      forkJoinPool.submit(() -> 
    //         liter.parallel().forEach((line) -> {
    //            final long docid = lc.incrementAndGet();
    //            if(docid % 1000 == 0)
    //               System.err.format("Processing line %d ('%s')%n", docid, _filename_in);
    //   
    //            String l = line.replace("\\t", "\t").replace("\\n", "\n");
    //            split_and_tokenize(
    //                  new StringReader(l),
    //                  String.format("%s:%d", _filename_in, docid),
    //                  sentenceSplitter.get(), 
    //                  tokenizer.get(), 
    //                  _level_filter,
    //                  _level_normalize,
    //                  _merge_types,
    //                  _merge_tokens,
    //                  _separator_sentence,
    //                  _separator_token,
    //                  _separator_desc,
    //                  w);
    //      })).get();

}

From source file:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java

@Test
public void testRateLimitingHandler() throws ExecutionException, InterruptedException {
    latch.countDown();/*  ww  w.ja v a2  s. co m*/
    latch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
    try {
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < N_THREADS; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        Thread.sleep(300);
        latch.countDown();
        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2"));
        }
    } finally {
        executor.shutdown();
    }

}

From source file:io.hops.security.TestUsersGroups.java

public void testConcurrentAddUser(int cacheTime, int cacheSize) throws Exception {
    Configuration conf = new Configuration();
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SECS, Integer.toString(cacheTime));
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SIZE, Integer.toString(cacheSize));
    HdfsStorageFactory.resetDALInitialized();
    HdfsStorageFactory.setConfiguration(conf);
    HdfsStorageFactory.formatStorage();/*from   ww w  . jav  a 2 s.  com*/
    UsersGroups.createSyncRow();

    final String userName = "user1";
    final String groupNmae = "group1";
    final int CONCURRENT_USERS = 100;
    ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_USERS);

    List<Callable<Integer>> callables = new ArrayList<>();
    for (int i = 0; i < CONCURRENT_USERS; i++) {
        callables.add(new AddUser(userName, groupNmae));
    }

    List<Future<Integer>> futures = executorService.invokeAll(callables);
    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    UsersGroups.clearCache();

    for (Future<Integer> f : futures) {
        try {
            f.get();
        } catch (ExecutionException ex) {
            ex.printStackTrace();
            fail();
        }
    }
}

From source file:org.piraso.server.spring.web.PirasoServletTest.java

@Test
public void testStartStopSuccess()
        throws IOException, ServletException, ExecutionException, InterruptedException {
    final AtomicBoolean fail = new AtomicBoolean(false);
    request.addParameter("service", "start");
    request.addParameter("preferences", mapper.writeValueAsString(new Preferences()));

    ExecutorService executor = Executors.newFixedThreadPool(2);

    Runnable startServiceRunnable = new Runnable() {
        public void run() {
            try {
                servlet.handleRequest(request, response);
            } catch (Exception e) {
                fail.set(true);/*  w ww .  j  av a 2  s  .  c  o  m*/
                e.printStackTrace();
            }
        }
    };

    Runnable logMessagesRunnable = new Runnable() {
        public void run() {
            try {
                MockHttpServletRequest request = CommonMockObjects.mockRequest(MONITORED_ADDR);
                request.addParameter("activity_uuid", "1");
                request.addParameter("service", "stop");

                // wait till service is available
                while (registry.getLogger(registry.createOrGetUser(pirasoRequest)) == null) {
                    Thread.sleep(100l);
                }

                servlet.handleRequest(request, new MockHttpServletResponse());
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

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

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

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }/*from   w w w.j  a va 2  s.c  om*/
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

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

@Test
public void testMultiClientsForServer() throws Exception {
    // Number of threads
    final int size = 30;

    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);
    }/*  w  ww. j av a2 s  .com*/

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

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

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallableForServer 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.test.test.MultipleRequestsForServerTest.java

@Test
public void testSingleClientsForServer() throws Exception {
    // Number of threads
    final int size = 20;

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

    IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);

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

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallableForServer(proxyService, i));
    }//  w ww .  j a  v a2s .  co  m

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallableForServer 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");

    LOG.debug("\n\n\n\n===========================");
    LOG.debug("And just sleep for empty pool");
    Thread.sleep(40000);
    IServiceSimple proxyService3 = clientSimple.getProxy(IServiceSimple.class);
    proxyService3.functionNumber1("1", "1");
}