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

The following examples show how to use java.util.concurrent.Executors#newCachedThreadPool() . 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 File: Chapter07Concurrency03.java    From Java-9-Cookbook with 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
Source File: CamelSinkAWSSQSITCase.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
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
Source File: ServerProviderConformanceTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
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 4
Source File: DisruptorConfigure.java    From youkefu with 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 5
Source File: B6660405.java    From openjdk-8 with 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 6
Source File: GeneralNonBlockingStepExecutionUtils.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
/**
 * 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 7
Source File: RootInputInitializerManager.java    From incubator-tez with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: AsyncControllerIT.java    From glowroot with 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 9
Source File: WorkLoadManager.java    From serve with 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 10
Source File: NettyAsyncHttpProvider.java    From ck with 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 11
Source File: Deadlock.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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 12
Source File: Client.java    From big-c with 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 13
Source File: RetryPost.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 14
Source File: DefaultConfigurationFactory.java    From Android-Application-ZJB with Apache License 2.0 4 votes vote down vote up
/**
 * Creates default implementation of task distributor
 */
public static Executor createTaskDistributor() {
    return Executors.newCachedThreadPool(createThreadFactory(Thread.NORM_PRIORITY, "uil-pool-d-"));
}
 
Example 15
Source File: ServerManager.java    From VideoConference with GNU General Public License v2.0 4 votes vote down vote up
public ServerManager()
{
    client=new Clients[CLIENT_NUMBER];
    clientTracker=new String [CLIENT_NUMBER];
    serverExeCutor=Executors.newCachedThreadPool();
}
 
Example 16
Source File: TestInterProcessReadWriteLock.java    From xian with Apache License 2.0 4 votes vote down vote up
@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 17
Source File: AsyncExecutor.java    From The-5zig-Mod with GNU General Public License v3.0 4 votes vote down vote up
public AsyncExecutor() {
	service = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Async Executor Pool #%1$d").build());
}
 
Example 18
Source File: QuartzCachedThreadPool.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize() throws SchedulerConfigException {
    this.executor = Executors.newCachedThreadPool();
}
 
Example 19
Source File: DeviceFarmUploader.java    From aws-device-farm-gradle-plugin with Apache License 2.0 4 votes vote down vote up
public DeviceFarmUploader(final AWSDeviceFarmClient api, final Logger logger) {
    this.api = api;
    this.logger = logger;
    this.uploadExecutor = Executors.newCachedThreadPool();
}
 
Example 20
Source File: MySocketClient.java    From wechatbot-xposed with Apache License 2.0 2 votes vote down vote up
protected void onCreate() {

        mExecutorService = Executors.newCachedThreadPool();
    }