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:es.upm.fiware.rss.settlement.ThreadPoolManager.java

@PostConstruct
public void init() {
    this.executorService = Executors.newCachedThreadPool();
}

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

public void run() {
    ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    bootstrap.setOption("child.tcpNoDelay", true);

    bootstrap.setPipelineFactory(new ECHttpServerPipelineFactory(spring));

    bootstrap.bind(new InetSocketAddress(port));
}

From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java

public void run(String connectionString) throws Exception {

    IMessageSender sendClient;//ww  w .j  ava2  s  .  c  o m
    CompletableFuture<Void> receiveTask;
    CompletableFuture<Void> fixUpTask;

    // send messages
    sendClient = ClientFactory.createMessageSenderFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"));
    this.sendMessagesAsync(sendClient);

    // wait for all messages to expire
    Thread.sleep(15 * 1000);

    ExecutorService executorService = Executors.newCachedThreadPool();
    // start the receiver tasks and the fixup tasks
    receiveTask = this.receiveMessagesAsync(connectionString, "BasicQueue", executorService);
    fixUpTask = this.pickUpAndFixDeadLetters(connectionString, "BasicQueue", sendClient, executorService);

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

    // cancel the running tasks
    receiveTask.cancel(true);
    fixUpTask.cancel(true);

    // wait for the tasks to complete
    CompletableFuture.allOf(sendClient.closeAsync(), receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException(t);
    }), fixUpTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException(t);
    })).join();

    executorService.shutdown();
}

From source file:com.blacklocus.qs.worker.TestApplication.java

@Override
public void run() {
    // simulated work
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.submit(new TaskGenerator());

    // actual qs-worker API
    QSAssembly.newBuilder().taskServices(new BlockingQueueQSTaskService(numbersMan))
            .logService(new SystemOutQSLogService()).workerIdService(new HostNameQSWorkerIdService())
            .workers(new TestWorkerPrintIdentity(), new TestWorkerPrintSquare(), new TestWorkerPrintZero(),
                    new TestWorkerUnmotivated())
            .build().run();/*from w  w  w .  j  a va  2  s. c  o m*/
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.Exports.java

@Override
public void register(Registry registry) {
    registry.add(new Builder.Factory<ExecutorService>() {
        @Override/*from  w  ww  . ja  v  a 2  s  . c o m*/
        public <S> ExecutorService create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            return Executors.newCachedThreadPool();
        }
    });

    registry.add(new Builder.Factory<ApacheConfigSettings>() {
        @Override
        public <S> ApacheConfigSettings create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            if (!ManagementConfiguration.isPlayback()
                    && properties.containsKey(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS)) {
                CloudCredentials cloudCredentials = (CloudCredentials) properties
                        .get(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS);
                cloudCredentials.applyConfig(profile, properties);
            }

            return new ApacheConfigSettings(profile, properties);
        }
    });

    registry.add(new Builder.Factory<HttpClientBuilder>() {
        @Override
        public <S> HttpClientBuilder create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            ApacheConfigSettings settings = builder.build(profile, service, ApacheConfigSettings.class,
                    properties);

            return settings.applyConfig(httpClientBuilder);
        }
    });
}

From source file:com.altamob.ads.connect.request.RequestAsyncTask.java

public void execute() {
    Executors.newCachedThreadPool().execute(new Runnable() {
        @Override//from  w  w  w . ja va  2s . c om
        public void run() {
            // Log.i(TAG, String.valueOf(requestCounter));
            String result = "";
            try {
                // Log.i("requestJson",
                // BuildJsonUtil.buridAdRequestJson(request));
                result = HttpUtil.httpGet(buildGetUrl(), request.getToken(), requestTimeOut);

                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.has("error")) {
                    Log.e(TAG, "Ad Service error:" + jsonObject.getString("error"));
                    callBack.OnFailure(AdError.SERVER_ERROR);
                } else {
                    callBack.OnCompleted(result);
                }
            } catch (IOException e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
                callBack.OnFailure(AdError.NETWORK_ERROR);
            } catch (Exception e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
                callBack.OnFailure(AdError.SERVER_ERROR);
            }
        }

    });
}

From source file:com.remobile.cordova.CordovaInterface.java

public CordovaInterface(CordovaPlugin plugin) {
    this.plugin = plugin;
    threadPool = Executors.newCachedThreadPool();
    this.permissionResultCallbacks = new CallbackMap();
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedLockTest.java

@Test
protected void test_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);
    final DistributedLock[] nodes = new DistributedLock[count];
    for (int i = 0; i < count; i++) {
        final DistributedLock node = new DistributedLock(dir);
        nodes[i] = node;//w  ww.jav  a2s  . c o  m
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    node.lock();
                    Thread.sleep(100 + RandomUtils.nextInt(100));
                    System.out.println("id: " + node.getId() + " is leader: " + node.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        node.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}

From source file:kindleclippings.quizlet.GetAccessToken.java

static JSONObject oauthDance() throws IOException, URISyntaxException, InterruptedException, JSONException {

    // start HTTP server, so when can get the authorization code
    InetSocketAddress addr = new InetSocketAddress(7777);
    HttpServer server = HttpServer.create(addr, 0);
    AuthCodeHandler handler = new AuthCodeHandler();
    server.createContext("/", handler);
    ExecutorService ex = Executors.newCachedThreadPool();
    server.setExecutor(ex);/*from w w w  .j  a v  a  2 s  .  com*/
    server.start();
    String authCode;
    try {
        Desktop.getDesktop()
                .browse(new URI(new StringBuilder("https://quizlet.com/authorize/")
                        .append("?scope=read%20write_set").append("&client_id=" + clientId)
                        .append("&response_type=code").append("&state=" + handler.state).toString()));

        authCode = handler.result.take();
    } finally {
        server.stop(0);
        ex.shutdownNow();
    }

    if (authCode == null || authCode.length() == 0)
        return null;

    HttpPost post = new HttpPost("https://api.quizlet.com/oauth/token");
    post.setHeader("Authorization", authHeader);

    post.setEntity(
            new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("grant_type", "authorization_code"),
                    new BasicNameValuePair("code", authCode))));
    HttpResponse response = new DefaultHttpClient().execute(post);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000);
    response.getEntity().writeTo(buffer);
    return new JSONObject(new String(buffer.toByteArray(), "UTF-8"));
}

From source file:net.sheehantech.cherry.pool.PooledPushClient.java

public PooledPushClient(SSLContext sslContext) {
    super(sslContext);
    executor = Executors.newCachedThreadPool();
}