Java Code Examples for java.util.concurrent.Executors#newCachedThreadPool()

The following examples show how to use java.util.concurrent.Executors#newCachedThreadPool() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Java-9-Cookbook   File: Chapter07Concurrency03.java    License: MIT License 6 votes vote down vote up
private static void demo4_submitCallableGetFuture() {
    CallableWorker callable = new CallableWorkerImpl("One", 2);

    System.out.println();
    System.out.println("Executors.newSingleThreadExecutor():");
    ExecutorService execService = Executors.newSingleThreadExecutor();
    submitCallableGetFuture(execService, 1, callable);

    System.out.println();
    System.out.println("Executors.newCachedThreadPool():");
    execService = Executors.newCachedThreadPool();
    submitCallableGetFuture(execService, 1, callable);

    System.out.println();
    int poolSize = 3;
    System.out.println("Executors.newFixedThreadPool(" + poolSize + "):");
    execService = Executors.newFixedThreadPool(poolSize);
    submitCallableGetFuture(execService, 1, callable);
}
 
Example 2
public void runTest(ConnectorPropertyFactory connectorPropertyFactory) throws Exception {
    connectorPropertyFactory.log();
    getKafkaConnectService().initializeConnectorBlocking(connectorPropertyFactory, 1);

    LOG.debug("Creating the consumer ...");
    ExecutorService service = Executors.newCachedThreadPool();

    CountDownLatch latch = new CountDownLatch(1);
    service.submit(() -> consumeMessages(latch));

    LOG.debug("Creating the producer and sending messages ...");
    produceMessages();

    LOG.debug("Waiting for the test to complete");
    if (latch.await(110, TimeUnit.SECONDS)) {
        assertTrue(received == expect,
                "Didn't process the expected amount of messages: " + received + " != " + expect);
    } else {
        fail(String.format("Failed to receive the messages within the specified time: received %d of %d",
                received, expect));
    }
}
 
Example 3
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example 4
Source Project: openjdk-8   File: B6660405.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Http Server
 */
public void startHttpServer() throws IOException {
    httpServer = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(0), 0);

    // create HttpServer context
    HttpContext ctx = httpServer.createContext("/test/", new MyHandler());

    executorService = Executors.newCachedThreadPool();
    httpServer.setExecutor(executorService);
    httpServer.start();
}
 
Example 5
/**
 * Workaround visibility restriction of {@code org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution#getExecutorService()}
 */
static synchronized ExecutorService getExecutorService() {
    if (executorService == null) {
        executorService = Executors.newCachedThreadPool(new NamingThreadFactory(new DaemonThreadFactory(), "org.jenkinsci.plugins.pipeline.maven.fix.jenkins49337.GeneralNonBlockingStepExecution"));
    }
    return executorService;
}
 
Example 6
@SuppressWarnings("rawtypes")
public RootInputInitializerManager(Vertex vertex, AppContext appContext,
                                   UserGroupInformation dagUgi) {
  this.appContext = appContext;
  this.vertex = vertex;
  this.eventHandler = appContext.getEventHandler();
  this.rawExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder()
      .setDaemon(true).setNameFormat("InputInitializer [" + this.vertex.getName() + "] #%d").build());
  this.executor = MoreExecutors.listeningDecorator(rawExecutor);
  this.dagUgi = dagUgi;
}
 
Example 7
Source Project: glowroot   File: AsyncControllerIT.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("async2")
public @ResponseBody DeferredResult<String> test() throws InterruptedException {
    new CreateTraceEntry().traceEntryMarker();
    final DeferredResult<String> result = new DeferredResult<String>();
    final ExecutorService executor = Executors.newCachedThreadPool();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            new CreateTraceEntry().traceEntryMarker();
            result.setResult("async2 world");
            executor.shutdown();
        }
    });
    return result;
}
 
Example 8
Source Project: serve   File: WorkLoadManager.java    License: Apache License 2.0 5 votes vote down vote up
public WorkLoadManager(ConfigManager configManager, EventLoopGroup backendGroup) {
    this.configManager = configManager;
    this.backendGroup = backendGroup;
    this.port = new AtomicInteger(9000);
    this.gpuCounter = new AtomicInteger(0);
    threadPool = Executors.newCachedThreadPool();
    workers = new ConcurrentHashMap<>();
}
 
Example 9
/**
 * Http Server
 */
public void startHttpServer(boolean shouldRetry) throws IOException {
    httpServer = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(0), 0);
    httpHandler = new MyHandler(shouldRetry);

    HttpContext ctx = httpServer.createContext("/test/", httpHandler);

    executorService = Executors.newCachedThreadPool();
    httpServer.setExecutor(executorService);
    httpServer.start();
}
 
Example 10
Source Project: big-c   File: Client.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get Executor on which IPC calls' parameters are sent.
 * If the internal reference counter is zero, this method
 * creates the instance of Executor. If not, this method
 * just returns the reference of clientExecutor.
 * 
 * @return An ExecutorService instance
 */
synchronized ExecutorService refAndGetInstance() {
  if (executorRefCount == 0) {
    clientExecutor = Executors.newCachedThreadPool(
        new ThreadFactoryBuilder()
        .setDaemon(true)
        .setNameFormat("IPC Parameter Sending Thread #%d")
        .build());
  }
  executorRefCount++;
  
  return clientExecutor;
}
 
Example 11
Source Project: ck   File: NettyAsyncHttpProvider.java    License: Apache License 2.0 5 votes vote down vote up
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
	super(new HashedWheelTimer(), 0, 0, config.getIdleConnectionTimeoutInMs(), TimeUnit.MILLISECONDS) ;
	socketChannelFactory = new NioClientSocketChannelFactory(
			Executors.newCachedThreadPool(),
			config.executorService());
	bootstrap = new ClientBootstrap(socketChannelFactory);
	this.config = config;
}
 
Example 12
Source Project: youkefu   File: DisruptorConfigure.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "deprecation" })
@Bean(name="multiupdate")   
   public Disruptor<UserDataEvent> multiupdate() {   
   	Executor executor = Executors.newCachedThreadPool();
   	 MultiUpdateEventFactory factory = new MultiUpdateEventFactory();
   	 Disruptor<UserDataEvent> disruptor = new Disruptor<UserDataEvent>(factory, 1024, executor, ProducerType.MULTI , new BlockingWaitStrategy());
   	 disruptor.handleEventsWith(new MultiUpdateEventHandler());
   	 disruptor.setDefaultExceptionHandler(new UKeFuExceptionHandler());
   	 disruptor.start();
        return disruptor;   
   }
 
Example 13
public void reset(final Iterable<ByteBuffer> responseContent) {
    synchronized (taskMonitor) {
        if (!pendingTasks.isEmpty()) {
            throw new AssertionError("pendingTasks should be empty, was " + pendingTasks);
        }
    }
    this.executor = Executors.newCachedThreadPool();
    this.responseWritten = new Event();
    this.responseClosed = new Event();
    this.responseContent = responseContent;
    this.taskException = null;
}
 
Example 14
public DeviceFarmUploader(final AWSDeviceFarmClient api, final Logger logger) {
    this.api = api;
    this.logger = logger;
    this.uploadExecutor = Executors.newCachedThreadPool();
}
 
Example 15
@Override
public void initialize() throws SchedulerConfigException {
    this.executor = Executors.newCachedThreadPool();
}
 
Example 16
public AsyncExecutor() {
	service = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Async Executor Pool #%1$d").build());
}
 
Example 17
/**
 * Creates default implementation of task distributor
 */
public static Executor createTaskDistributor() {
    return Executors.newCachedThreadPool(createThreadFactory(Thread.NORM_PRIORITY, "uil-pool-d-"));
}
 
Example 18
@Test
public void     testGetParticipantNodes() throws Exception
{
    final int               READERS = 20;
    final int               WRITERS = 8;

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        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
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 19
public ServerManager()
{
    client=new Clients[CLIENT_NUMBER];
    clientTracker=new String [CLIENT_NUMBER];
    serverExeCutor=Executors.newCachedThreadPool();
}
 
Example 20
Source Project: wechatbot-xposed   File: MySocketClient.java    License: Apache License 2.0 2 votes vote down vote up
protected void onCreate() {

        mExecutorService = Executors.newCachedThreadPool();
    }