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.cognifide.aet.job.common.collectors.source.SourceCollector.java

private byte[] getContent() throws ProcessingException {
    byte[] content;
    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
        @Override/*  ww  w. java  2 s.com*/
        public Object call() throws IOException {
            return httpRequestBuilder.executeRequest().getContent();
        }
    };
    Future<Object> future = executor.submit(task);
    try {
        content = (byte[]) future.get(timeoutValue, TimeUnit.MILLISECONDS);
    } catch (TimeoutException | InterruptedException | ExecutionException e) {
        throw new ProcessingException(e.getMessage(), e);
    } finally {
        future.cancel(true);
    }
    return content;
}

From source file:com.googlecode.vfsjfilechooser2.plaf.basic.BasicVFSDirectoryModel.java

/**
 *
 * @param filechooser// w  w  w.  j  av a  2s  .c o  m
 */
public BasicVFSDirectoryModel(VFSJFileChooser filechooser) {
    this.filechooser = filechooser;
    this.executor = Executors.newCachedThreadPool();
    validateFileCache();
}

From source file:rk.java.compute.cep.ComputeService.java

public ComputeService(BlockingQueue<IPriceTick> queue, final int numberOfTickSources,
        IPriceEventSink eventbus) {//from   w w w.ja  v a  2 s.  c  o  m
    this.feedQueue = queue;
    this.numberOfTickSources = numberOfTickSources;
    this.eventbus = eventbus;
    this.handlerCache = new ConcurrentHashMap<String, Compute>();
    this.stopWatch = new StopWatch("Dispatcher Task");
    executorService = Executors.newCachedThreadPool();
    ecs = new ExecutorCompletionService<StopWatch>(executorService);
    dispatchTaskFuture = ecs.submit(new Callable<StopWatch>() {
        @Override
        public StopWatch call() throws Exception {
            stopWatch.start();
            run();
            stopWatch.stop();
            return stopWatch;
        }
    });
}

From source file:cc.osint.graphd.client.ProtographClient.java

public boolean connect() throws Exception {
    bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    ProtographClientPipelineFactory pipelineFactory = new ProtographClientPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    channel = future.awaitUninterruptibly().getChannel();

    if (!future.isSuccess()) {
        connected = false;/*from ww  w .  ja v  a  2  s.  com*/
        future.getCause().printStackTrace();
        bootstrap.releaseExternalResources();
        log.info("Connection failure: " + host + ":" + port);
    } else {
        connected = true;
        log.info("Connection success: " + host + ":" + port);
    }
    return connected;
}

From source file:com.opengamma.language.config.ConfigurationFactoryBean.java

protected Configuration getConfiguration() {
    try {//from ww w.j ava 2s  . co m
        FudgeMsg msg = new RemoteConfiguration(getConfigurationURIAsURI()).getConfigurationMsg();
        Validater validater = UriEndPointDescriptionProvider.validater(Executors.newCachedThreadPool(),
                getConfigurationURIAsURI());
        return new Configuration(getFudgeContext(), msg, validater);

    } catch (UniformInterfaceException404NotFound ex) {
        return new Configuration(getFudgeContext(), getFudgeContext().newMessage(), null);
    }
}

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

@Test
public void testMultiClient() throws Exception {
    CuratorFramework client1 = null;/*from  w  w  w . j a  va2  s . co m*/
    CuratorFramework client2 = null;
    try {
        {
            CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                    new RetryOneTime(1));
            try {
                client.start();
                DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
                barrier.setBarrier();
            } finally {
                IOUtils.closeQuietly(client);
            }
        }

        client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));

        List<Future<Object>> futures = Lists.newArrayList();
        ExecutorService service = Executors.newCachedThreadPool();
        for (final CuratorFramework c : new CuratorFramework[] { client1, client2 }) {
            Future<Object> future = service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    c.start();
                    DistributedBarrier barrier = new DistributedBarrier(c, "/barrier");
                    barrier.waitOnBarrier(10, TimeUnit.MILLISECONDS);
                    return null;
                }
            });
            futures.add(future);
        }

        Thread.sleep(1000);
        {
            CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                    new RetryOneTime(1));
            try {
                client.start();
                DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
                barrier.removeBarrier();
            } finally {
                IOUtils.closeQuietly(client);
            }
        }

        for (Future<Object> f : futures) {
            f.get();
        }
    } finally {
        IOUtils.closeQuietly(client1);
        IOUtils.closeQuietly(client2);
    }
}

From source file:com.easarrive.image.thumbor.executer.service.impl.SQSNotificationHandlerForThumbor.java

private List<NotificationHandleResult<Message, Boolean>> ergodicS3EventMessageRecord(final Message message,
        S3EventMessageContent messageContent) throws AWSPluginException {
    List<S3EventMessageRecord> recordList = messageContent.getRecords();
    if (recordList == null) {
        throw new AWSPluginException("The S3EventMessageRecord list is null");
    }//from  w  w w.j a va2s  .  co  m
    if (recordList.size() < 1) {
        throw new AWSPluginException("The S3EventMessageRecord list is empty");
    }

    ExecutorService executorService = Executors.newCachedThreadPool();
    List<Future<NotificationHandleResult<Message, Boolean>>> resultList = new ArrayList<Future<NotificationHandleResult<Message, Boolean>>>();
    for (final S3EventMessageRecord s3EventMessageRecord : recordList) {
        Future<NotificationHandleResult<Message, Boolean>> future = executorService.submit(
                new SQSNotificationHandlerForThumborCallable(message, s3EventMessageRecord, generatePicture));
        resultList.add(future);
    }

    List<NotificationHandleResult<Message, Boolean>> resutList = new ArrayList<NotificationHandleResult<Message, Boolean>>();
    //??
    for (Future<NotificationHandleResult<Message, Boolean>> fs : resultList) {
        try {
            NotificationHandleResult<Message, Boolean> result = fs.get();
            if (logger.isInfoEnabled()) {
                logger.info("The SQS message record ({}) result to handle is {}", result.getMessageId(),
                        result.getData());
            }
            resutList.add(result);
            if (!result.getData()) {
                break;
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.getMessage(), e);
            }
        } finally {
            //????????
            executorService.shutdown();
        }
    }
    return resutList;
}

From source file:com.buaa.cfs.common.portmap.Portmap.java

void start(final int idleTimeMilliSeconds, final SocketAddress tcpAddress, final SocketAddress udpAddress) {

    tcpServer = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    tcpServer.setPipelineFactory(new ChannelPipelineFactory() {
        private final HashedWheelTimer timer = new HashedWheelTimer();
        private final IdleStateHandler idleStateHandler = new IdleStateHandler(timer, 0, 0,
                idleTimeMilliSeconds, TimeUnit.MILLISECONDS);

        @Override//from   w w w  .  j ava 2s.co  m
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(RpcUtil.constructRpcFrameDecoder(), RpcUtil.STAGE_RPC_MESSAGE_PARSER,
                    idleStateHandler, handler, RpcUtil.STAGE_RPC_TCP_RESPONSE);
        }
    });

    udpServer = new ConnectionlessBootstrap(new NioDatagramChannelFactory(Executors.newCachedThreadPool()));

    udpServer.setPipeline(
            Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER, handler, RpcUtil.STAGE_RPC_UDP_RESPONSE));

    tcpChannel = tcpServer.bind(tcpAddress);
    udpChannel = udpServer.bind(udpAddress);
    allChannels.add(tcpChannel);
    allChannels.add(udpChannel);

    LOG.info("Portmap server started at tcp://" + tcpChannel.getLocalAddress() + ", udp://"
            + udpChannel.getLocalAddress());
}

From source file:com.google.cloud.bigtable.hbase.TestCreateTable.java

/**
 * Requirement 1.8 - Table names must match [_a-zA-Z0-9][-_.a-zA-Z0-9]*
 *//*from w w  w .  ja va  2s  .c om*/
@Test(timeout = 1000l * 60 * 4)
public void testTableNames() throws IOException {
    String shouldTest = System.getProperty("bigtable.test.create.table", "true");
    if (!"true".equals(shouldTest)) {
        return;
    }
    String[] goodNames = { "a", "1", "_", // Really?  Yuck.
            "_x", "a-._5x", "_a-._5x",
            // TODO(sduskis): Join the last 2 strings once the Bigtable backend supports table names
            // longer than 50 characters.
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi", "jklmnopqrstuvwxyz1234567890_-." };
    String[] badNames = { "-x", ".x", "a!", "a@", "a#", "a$", "a%", "a^", "a&", "a*", "a(", "a+", "a=", "a~",
            "a`", "a{", "a[", "a|", "a\\", "a/", "a<", "a,", "a?",
            "a" + RandomStringUtils.random(10, false, false) };

    final Admin admin = getConnection().getAdmin();

    for (String badName : badNames) {
        boolean failed = false;
        try {
            admin.createTable(new HTableDescriptor(TableName.valueOf(badName))
                    .addFamily(new HColumnDescriptor(COLUMN_FAMILY)));
        } catch (IllegalArgumentException e) {
            failed = true;
        }
        Assert.assertTrue("Should fail as table name: '" + badName + "'", failed);
    }

    final TableName[] tableNames = admin.listTableNames();

    List<ListenableFuture<Void>> futures = new ArrayList<>();
    ListeningExecutorService es = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    for (final String goodName : goodNames) {
        futures.add(es.submit(new Callable<Void>() {
            @Override
            public Void call() throws IOException {
                createTable(admin, goodName, tableNames);
                return null;
            }
        }));
    }
    try {
        try {
            Futures.allAsList(futures).get(3, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } finally {
        es.shutdownNow();
    }
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

public DatabasesBackend(Context context) {
    this(context, null, null, Executors.newCachedThreadPool(), Executors.newFixedThreadPool(1));
}