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:guru.nidi.languager.check.LinkChecker.java

public List<FindResult<String>> findBrokenLinks() {
    ExecutorService executor = Executors.newCachedThreadPool();
    final List<FindResult<String>> res = Collections.synchronizedList(new ArrayList<FindResult<String>>());
    final Set<String> urls = new HashSet<>();
    int lineNum = 1;

    for (MessageLine line : contents.subList(1, contents.size())) {
        lineNum++;/*  ww  w  .ja va2 s.co  m*/
        int col = 1;
        int elemNum = 0;
        for (String element : line) {
            final Matcher matcher = LINK_PATTERN.matcher(element);
            while (matcher.find()) {
                final String url = matcher.group();
                if (!urls.contains(url)) {
                    urls.add(url);
                    executor.submit(new LinkValidator(res, url,
                            new SourcePosition(file, lineNum, col + elemNum + matcher.start())));
                }
            }
            elemNum++;
            col += element.length();
        }
    }
    executor.shutdown();
    try {
        executor.awaitTermination(20, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        //ignore
    }
    return res;
}

From source file:com.mobilesolutionworks.android.httpcache.WorksHttpCacheService.java

@Override
public void onCreate() {
    super.onCreate();

    mHandler = new Handler();

    mQueues = new HashSet<String>();
    mExecutors = Executors.newCachedThreadPool();

    mConfiguration = HttpCacheConfiguration.configure(this);
}

From source file:com.smith.http.webservice.WebSocketServer.java

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

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory());

    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(port));

    System.out.println("Web socket server started at port " + port + '.');
    System.out.println("Open your browser and navigate to http://localhost:" + port + '/');
}

From source file:net.solarnetwork.node.io.serial.rxtx.test.SerialConnectionTests.java

@Before
public void setup() {
    executor = Executors.newCachedThreadPool();
}

From source file:com.buaa.cfs.common.oncrpc.SimpleUdpServer.java

public void run() {
    // Configure the client.
    DatagramChannelFactory f = new NioDatagramChannelFactory(Executors.newCachedThreadPool(), workerCount);

    server = new ConnectionlessBootstrap(f);
    server.setPipeline(/*from ww  w .j av a2 s  . com*/
            Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER, rpcProgram, RpcUtil.STAGE_RPC_UDP_RESPONSE));

    server.setOption("broadcast", "false");
    server.setOption("sendBufferSize", SEND_BUFFER_SIZE);
    server.setOption("receiveBufferSize", RECEIVE_BUFFER_SIZE);

    // Listen to the UDP port
    ch = server.bind(new InetSocketAddress(port));
    InetSocketAddress socketAddr = (InetSocketAddress) ch.getLocalAddress();
    boundPort = socketAddr.getPort();

    LOG.info("Started listening to UDP requests at port " + boundPort + " for " + rpcProgram
            + " with workerCount " + workerCount);
}

From source file:com.codefollower.lealone.omid.tso.TSOTestBase.java

public static void setupClient() throws IOException {

    // *** Start the Netty configuration ***

    Configuration conf = HBaseConfiguration.create();
    conf.set("tso.host", "localhost");
    conf.setInt("tso.port", 1234);

    // Start client with Nb of active threads = 3 as maximum.
    channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), 3);
    // Create the bootstrap
    // Create the global ChannelGroup
    channelGroup = new DefaultChannelGroup(TransactionClient.class.getName());
    // Create the associated Handler
    clientHandler = new TestClientHandler(conf);

    // *** Start the Netty running ***

    System.out.println("PARAM MAX_ROW: " + ClientHandler.MAX_ROW);
    System.out.println("PARAM DB_SIZE: " + ClientHandler.DB_SIZE);

    // Connect to the server, wait for the connection and get back the channel
    clientHandler.await();//from   w w  w  . j  a v a2  s . co  m

    // Second client handler
    secondClientHandler = new TestClientHandler(conf);

    // *** Start the Netty running ***

    System.out.println("PARAM MAX_ROW: " + ClientHandler.MAX_ROW);
    System.out.println("PARAM DB_SIZE: " + ClientHandler.DB_SIZE);
}

From source file:com.oneops.util.ReliableExecutor.java

public ReliableExecutor() {
    executors = (ThreadPoolExecutor) Executors.newCachedThreadPool();
}

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

@Test
public void testMultiClient() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
    final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger max = new AtomicInteger(0);
    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < QTY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override/*from   w ww.jav  a2s  . com*/
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        timing.session(), timing.connection(), new RetryOneTime(1));
                try {
                    client.start();
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));
                } finally {
                    IOUtils.closeQuietly(client);
                }

                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> f : futures) {
        f.get();
    }
    Assert.assertEquals(count.get(), 0);
    Assert.assertEquals(max.get(), QTY);
}

From source file:org.imgedit.webservice.WebServerBootstrap.java

@PostConstruct
private void initialize() {
    if (cliHandler.isParsedSuccessfully()) {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        // NOTE: Add "new LoggingHandler(InternalLogLevel.ERROR)," for debug.
                        new HttpRequestDecoder(), new HttpChunkAggregator(MAX_FRAME_SIZE),
                        new HttpResponseEncoder(), new HttpContentCompressor(), webServerHandler);
            }/*  w w w.  j ava  2 s  . c o  m*/
        });

        // Bind and start to accept incoming connections.
        LOG.info(String.format("Working in the '%s' directory, listening on the %s port...",
                cliHandler.getBaseDirectory(), cliHandler.getPort()));
        bootstrap.bind(new InetSocketAddress(cliHandler.getPort()));
    }
}

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

@Test
public void testGetParticipantNodes() throws Exception {
    final int READERS = 20;
    final int WRITERS = 8;

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/* w w  w  . j  a v a 2 s.co m*/
        client.start();

        final CountDownLatch latch = new CountDownLatch(READERS + WRITERS);
        final CountDownLatch readLatch = new CountDownLatch(READERS);
        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");

        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < READERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    lock.readLock().acquire();
                    latch.countDown();
                    readLatch.countDown();
                    return null;
                }
            });
        }
        for (int i = 0; i < WRITERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Assert.assertTrue(readLatch.await(10, TimeUnit.SECONDS));
                    latch.countDown(); // must be before as there can only be one writer
                    lock.writeLock().acquire();
                    return null;
                }
            });
        }

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Collection<String> readers = lock.readLock().getParticipantNodes();
        Collection<String> writers = lock.writeLock().getParticipantNodes();

        Assert.assertEquals(readers.size(), READERS);
        Assert.assertEquals(writers.size(), WRITERS);
    } finally {
        IOUtils.closeQuietly(client);
    }
}