Example usage for java.util.concurrent Executors newCachedThreadPool

List of usage examples for java.util.concurrent Executors newCachedThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newCachedThreadPool.

Prototype

public static ExecutorService newCachedThreadPool() 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

Usage

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testOverSubscribed() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    ExecutorService service = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(service);
    try {/*from w w w  .  j a  v a 2  s.c  o  m*/
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) {
                        @Override
                        protected List<String> getChildrenForEntering() throws Exception {
                            semaphore.release();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            return super.getChildrenForEntering();
                        }
                    };
                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));
                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    return null;
                }
            });
        }

        Assert.assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter
        latch.countDown();

        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.take().get(); // to check for assertions
        }
    } finally {
        service.shutdown();
        IOUtils.closeQuietly(client);
    }
}

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.SpringConfig.java

@Bean
public ExecutorService executorService() {
    ExecutorService bean = Executors.newCachedThreadPool();
    regestryService.registerService(new Shutdownable() {
        @Override/*w ww  .  j  a  va2s .  com*/
        public void shutdown() {
            bean.shutdown();
        }
    });
    return bean;
}

From source file:org.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java

@BeforeClass
public static void beforeClass() throws IOException {
    ExtensionUtils.createExtensionModule(LogStreamExtension.MODULE_NAME, LogStreamExtension.class,
            EmptySubsystemParser.class.getPackage());
    executorService = Executors.newCachedThreadPool();
}

From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java

@Test
public void testSparseUseNoReap() throws Exception {
    final int THRESHOLD = 3000;

    Timing timing = new Timing();
    Reaper reaper = null;// w ww.  j  av a  2 s.c  o  m
    Future<Void> watcher = null;
    CuratorFramework client = makeClient(timing, null);
    try {
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/one/two/three");

        Assert.assertNotNull(client.checkExists().forPath("/one/two/three"));

        final Queue<Reaper.PathHolder> holders = new ConcurrentLinkedQueue<Reaper.PathHolder>();
        final ExecutorService pool = Executors.newCachedThreadPool();
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1) {
            @Override
            public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
                final Reaper.PathHolder pathHolder = (Reaper.PathHolder) command;
                holders.add(pathHolder);
                final ScheduledFuture<?> f = super.schedule(command, delay, unit);
                pool.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        f.get();
                        holders.remove(pathHolder);
                        return null;
                    }
                });
                return f;
            }
        };

        reaper = new Reaper(client, service, THRESHOLD);
        reaper.start();
        reaper.addPath("/one/two/three");

        long start = System.currentTimeMillis();
        boolean emptyCountIsCorrect = false;
        while (((System.currentTimeMillis() - start) < timing.forWaiting().milliseconds())
                && !emptyCountIsCorrect) // need to loop as the Holder can go in/out of the Reaper's DelayQueue
        {
            for (Reaper.PathHolder holder : holders) {
                if (holder.path.endsWith("/one/two/three")) {
                    emptyCountIsCorrect = (holder.emptyCount > 0);
                    break;
                }
            }
            Thread.sleep(1);
        }
        Assert.assertTrue(emptyCountIsCorrect);

        client.create().forPath("/one/two/three/foo");

        Thread.sleep(2 * (THRESHOLD / Reaper.EMPTY_COUNT_THRESHOLD));
        Assert.assertNotNull(client.checkExists().forPath("/one/two/three"));
        client.delete().forPath("/one/two/three/foo");

        Thread.sleep(THRESHOLD);
        timing.sleepABit();

        Assert.assertNull(client.checkExists().forPath("/one/two/three"));
    } finally {
        if (watcher != null) {
            watcher.cancel(true);
        }
        IOUtils.closeQuietly(reaper);
        IOUtils.closeQuietly(client);
    }
}

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

/**
 * Creates the KeyVaultClient using the credentials specified in the Utility
 * class.//from  ww  w .j  a v a 2  s  .  c om
 * 
 * @return
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws InterruptedException
 * @throws ExecutionException
 */
public static KeyVaultClient GetKeyVaultClient()
        throws URISyntaxException, MalformedURLException, InterruptedException, ExecutionException {
    if (Utility.AuthClientId == null || Utility.AuthClientId.isEmpty() || Utility.AuthClientSecret == null
            || Utility.AuthClientSecret.isEmpty()) {
        throw new IllegalArgumentException("Invalid AuthClientID or AuthClientSecret specified.");
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    ExecutorService executorService = Executors.newCachedThreadPool();
    KVCredentials creds = new KVCredentials(Utility.AuthClientId, Utility.AuthClientSecret);
    KeyVaultClient cloudVault = new KeyVaultClientImpl(httpClientBuilder, executorService, creds);
    return cloudVault;
}

From source file:byps.test.servlet.MyServerIF.java

@Override
public int callClientParallel(int nbOfCalls) throws RemoteException {
    if (log.isDebugEnabled())
        log.debug("callClientParallel(" + nbOfCalls);
    final ClientIF clientIF = getClientIF();
    final AtomicInteger ret = new AtomicInteger(0);
    ExecutorService tpool = Executors.newCachedThreadPool();
    for (int i = 0; i < nbOfCalls; i++) {
        Runnable run = new Runnable() {
            public void run() {
                try {
                    if (log.isDebugEnabled())
                        log.debug("clientIF.incrementInt(");
                    int v = clientIF.incrementInt(0);
                    if (log.isDebugEnabled())
                        log.debug(")clientIF.incrementInt");
                    ret.addAndGet(v);/*from  w w  w  .  jav a2  s.  c o  m*/
                } catch (Exception e) {
                    log.error(e);
                }
            }
        };
        tpool.execute(run);
    }
    tpool.shutdown();
    try {
        tpool.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new BException(BExceptionC.CANCELLED, e.toString(), e);
    }
    if (log.isDebugEnabled())
        log.debug(")callClientParallel");
    return ret.get();
}

From source file:com.ecarinfo.frame.httpserver.core.http.HttpSnoopClientPipelineFactory.java

public void request(HttpMethod method, Map<String, String> params, Object dto) {
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(false));
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
        future.getCause().printStackTrace();
        bootstrap.releaseExternalResources();
        return;/*from www  .  j a v a 2  s . c o m*/
    }
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri.getRawPath());
    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    String content = "";
    if (dto != null) {
        request.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        content = JsonUtils.Object2JsonString(dto);
    } else if (!CollectionUtils.isEmpty(params)) {
        StringBuilder buf = new StringBuilder("");
        for (Entry<String, String> e : params.entrySet()) {
            if (buf.length() > 0) {
                buf.append("&");
            }
            buf.append(e.getKey()).append("=").append(e.getValue());
        }
        content = buf.toString();
    }
    ChannelBuffer cb = ChannelBuffers.copiedBuffer(content, Charset.defaultCharset());
    request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, cb.readableBytes());
    request.setContent(cb);
    channel.write(request);
    channel.getCloseFuture().awaitUninterruptibly();
    bootstrap.releaseExternalResources();
}

From source file:com.fluidops.fedx.FedX.java

protected FedX(Config config, Cache cache, Statistics statistics, EndpointListProvider endpointListProvider,
        SummaryProvider summaryProvider) {
    this.config = config;
    this.cache = cache;
    this.statistics = statistics;
    this.endpointListProvider = endpointListProvider;
    this.summaryProvider = summaryProvider;

    // initialize httpclient parameters
    HttpClientBuilder httpClientBuilder = HttpClientBuilders.getSSLTrustAllHttpClientBuilder();
    httpClientBuilder.setMaxConnTotal(config.getMaxHttpConnectionCount());
    httpClientBuilder.setMaxConnPerRoute(config.getMaxHttpConnectionCountPerRoute());

    //httpClientBuilder.evictExpiredConnections();
    //httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    //httpClientBuilder.setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS);
    //httpClientBuilder.disableAutomaticRetries();

    //      httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy(){
    ///*from w  w  w.j a v  a  2s .  c o  m*/
    //          @Override
    //          public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    //              return 0;
    //          }});

    httpClient = httpClientBuilder.build();

    synchronized (log) {
        if (monitoring == null) {
            monitoring = MonitoringFactory.createMonitoring(config);
        }
    }

    executor = Executors.newCachedThreadPool();

    scheduler = new ControlledWorkerScheduler(config.getWorkerThreads(), "Evaluation Scheduler");
    if (log.isDebugEnabled()) {
        log.debug("Scheduler for async operations initialized with " + config.getWorkerThreads()
                + " worker threads.");
    }

    // initialize prefix declarations, if any
    String prefixFile = config.getPrefixDeclarations();
    if (prefixFile != null) {
        prefixDeclarations = new Properties();
        try {
            prefixDeclarations.load(new FileInputStream(new File(prefixFile)));
        } catch (IOException e) {
            throw new FedXRuntimeException("Error loading prefix properties: " + e.getMessage());
        }
    }
    open = true;
}

From source file:org.openwms.common.comm.app.DriverConfig.java

@Bean
MessageChannel commonExceptionChannel() {
    return MessageChannels.executor(Executors.newCachedThreadPool()).get();
}

From source file:com.redhat.red.build.koji.it.AbstractIT.java

@Before
public void setup() {
    System.out.println("\n\n #### SETUP: " + name.getMethodName() + " #### \n\n");
    passwordManager = new MemoryPasswordManager();
    factory = new HttpFactory(passwordManager);
    System.out.println("\n\n #### START: " + name.getMethodName() + " #### \n\n");

    String buildDir = System.getProperty("project.build.directory", "target");

    downloadDir = Paths.get(buildDir, "downloads", name.getMethodName()).toFile();
    downloadDir.mkdirs();//ww  w. j av a  2s  .co  m

    executor = Executors.newCachedThreadPool();
}