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

The following are Jave code examples for showing how to use newCachedThreadPool() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ysoserial-modified   File: JenkinsCLI.java   View Source Code Vote up 7 votes
public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
    System.err.println("* Opening socket " + isa);
    Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
    s.setKeepAlive(true);
    s.setTcpNoDelay(true);

    System.err.println("* Opening channel");
    OutputStream outputStream = s.getOutputStream();
    DataOutputStream dos = new DataOutputStream(outputStream);
    dos.writeUTF("Protocol:CLI-connect");
    ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread ( Runnable r ) {
            Thread t = new Thread(r, "Channel");
            t.setDaemon(true);
            return t;
        }
    });
    Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
    System.err.println("* Channel open");
    return c;
}
 
Example 2
Project: Java-9-Cookbook   File: Chapter07Concurrency03.java   View Source Code Vote up 7 votes
private static void demo5_submitCallableGetResult() {
    CallableWorker callable = new CallableWorkerImpl("One", 2);

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

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

    System.out.println();
    int poolSize = 3;
    System.out.println("Executors.newFixedThreadPool(" + poolSize + "):");
    execService = Executors.newFixedThreadPool(poolSize);
    submitCallableGetResult(execService, 1, callable);
}
 
Example 3
Project: CrypDist   File: Client.java   View Source Code Vote up 6 votes
public HashMap<String,String> broadCastMessageResponseWithIp(String message) {

        ExecutorService executor = Executors.newCachedThreadPool();
        HashMap<Peer,Future<String>> futures = new HashMap<>();

        for(Peer peer:peerList.keySet()) {
            Callable<String> task = new ResponsedMessageTask(peer,message);
            Future<String> future = executor.submit(task);
            futures.put(peer,future);
        }

        HashMap<String,String> result = new HashMap<>();


        for(Map.Entry<Peer,Future<String>> entry : futures.entrySet()) {
            try {
                String res  = entry.getValue().get();
                if(res != null && !res.equals(""))
                    result.put(entry.getKey().getAddress().toString(),res);
            } catch (Exception e) {}
        }

        return result;
    }
 
Example 4
Project: ArtOfAndroid   File: MainActivity.java   View Source Code Vote up 6 votes
private void runThreadPool() {
    Runnable command = new Runnable(){
        @Override
        public void run() {
            Log.d(TAG, Thread.currentThread().getName());
        }
    };

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    fixedThreadPool.execute(command);

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.execute(command);

    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
    //scheduledThreadPool.schedule(command, 2, TimeUnit.SECONDS);                             //延迟2秒后执行
    scheduledThreadPool.scheduleAtFixedRate(command, 10, 2000, TimeUnit.MILLISECONDS);      //延迟10ms后,每隔1000ms执行一次

    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    singleThreadExecutor.execute(command);
}
 
Example 5
Project: LivroJavaComoProgramar10Edicao   File: SharedArrayTest.java   View Source Code Vote up 5 votes
public static void main(String[] arg)
{
   // construct the shared object
   SimpleArray sharedSimpleArray = new SimpleArray(6);

   // create two tasks to write to the shared SimpleArray
   ArrayWriter writer1 = new ArrayWriter(1, sharedSimpleArray);
   ArrayWriter writer2 = new ArrayWriter(11, sharedSimpleArray);

   // execute the tasks with an ExecutorService
   ExecutorService executorService = Executors.newCachedThreadPool();
   executorService.execute(writer1);
   executorService.execute(writer2);

   executorService.shutdown();

   try
   {
      // wait 1 minute for both writers to finish executing
      boolean tasksEnded = 
         executorService.awaitTermination(1, TimeUnit.MINUTES);

      if (tasksEnded)
      {
         System.out.printf("%nContents of SimpleArray:%n");
         System.out.println(sharedSimpleArray); // print contents
      }
      else
         System.out.println(
            "Timed out while waiting for tasks to finish.");
   } 
   catch (InterruptedException ex)
   {
      ex.printStackTrace();
   } 
}
 
Example 6
Project: openjdk-jdk10   File: Deadlock.java   View Source Code Vote up 5 votes
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 7
Project: shabdiz   File: ExperimentManager.java   View Source Code Vote up 5 votes
protected void clearCachedShabdizFilesOnAllHosts(ApplicationNetwork network) throws IOException, InterruptedException, TimeoutException, ExecutionException {

        LOGGER.info("Attempting to remove all shabdiz cached files on {} hosts", network.size());
        final ExecutorService executor = Executors.newCachedThreadPool();
        try {
            final List<CompletableFuture<Void>> future_deletions = new ArrayList<>();

            for (final ApplicationDescriptor descriptor : network) {
                final Host host = descriptor.getHost();
                final CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {

                    final String host_name = host.getName();
                    LOGGER.info("removing shabdiz cached files on {}", host_name);
                    try {
                        AgentBasedJavaProcessBuilder.clearCachedFilesOnHost(host);
                        LOGGER.info("done removing shabdiz cached files on {}", host_name);
                    }
                    catch (final Exception e) {
                        LOGGER.error("failed to remove shabdiz cached files on " + host_name, e);
                        throw new RuntimeException(e);
                    }
                }, executor);
                future_deletions.add(future);
            }

            CompletableFuture.allOf(future_deletions.toArray(new CompletableFuture[future_deletions.size()])).get(CACHE_DELETION_TIMEOUT.getLength(), CACHE_DELETION_TIMEOUT.getTimeUnit());
        }
        finally {
            executor.shutdownNow();
        }

    }
 
Example 8
Project: openjdk-jdk10   File: JdiInitiator.java   View Source Code Vote up 5 votes
VirtualMachine timedVirtualMachineCreation(Callable<VirtualMachine> creator,
        Callable<Integer> processComplete) throws Exception {
    VirtualMachine result;
    ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
        Thread thread = Executors.defaultThreadFactory().newThread(runnable);
        thread.setDaemon(true);
        return thread;
    });
    try {
        Future<VirtualMachine> future = executor.submit(creator);
        if (processComplete != null) {
            executor.submit(() -> {
                Integer i = processComplete.call();
                future.cancel(true);
                return i;
            });
        }

        try {
            result = future.get(connectTimeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            future.cancel(true);
            throw ex;
        }
    } finally {
        executor.shutdownNow();
    }
    return result;
}
 
Example 9
Project: openjdk-jdk10   File: LightWeightHttpServer.java   View Source Code Vote up 5 votes
public static void initServer() throws IOException {

        Logger logger = Logger.getLogger("com.sun.net.httpserver");
        ConsoleHandler ch = new ConsoleHandler();
        logger.setLevel(Level.ALL);
        ch.setLevel(Level.ALL);
        logger.addHandler(ch);

        String root = System.getProperty("test.src") + "/docs";
        InetSocketAddress addr = new InetSocketAddress(0);
        httpServer = HttpServer.create(addr, 0);
        if (httpServer instanceof HttpsServer) {
            throw new RuntimeException("should not be httpsserver");
        }
        httpsServer = HttpsServer.create(addr, 0);
        HttpHandler h = new FileServerHandler(root);

        HttpContext c1 = httpServer.createContext("/files", h);
        HttpContext c2 = httpsServer.createContext("/files", h);
        HttpContext c3 = httpServer.createContext("/echo", new EchoHandler());
        redirectHandler = new RedirectHandler("/redirect");
        redirectHandlerSecure = new RedirectHandler("/redirect");
        HttpContext c4 = httpServer.createContext("/redirect", redirectHandler);
        HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure);
        HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler());
        HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler());
        redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
        redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
        HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler);
        HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure);
        delayHandler = new DelayHandler();
        HttpContext c8 = httpServer.createContext("/delay", delayHandler);
        HttpContext c81 = httpsServer.createContext("/delay", delayHandler);

        executor = Executors.newCachedThreadPool();
        httpServer.setExecutor(executor);
        httpsServer.setExecutor(executor);
        ctx = new SimpleSSLContext().get();
        httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx));
        httpServer.start();
        httpsServer.start();

        port = httpServer.getAddress().getPort();
        System.out.println("HTTP server port = " + port);
        httpsport = httpsServer.getAddress().getPort();
        System.out.println("HTTPS server port = " + httpsport);
        httproot = "http://127.0.0.1:" + port + "/";
        httpsroot = "https://127.0.0.1:" + httpsport + "/";

        proxy = new ProxyServer(0, false);
        proxyPort = proxy.getPort();
        System.out.println("Proxy port = " + proxyPort);
    }
 
Example 10
Project: think-in-java   File: PriorityBlockingQueueDemo.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception
{
    Random rand = new Random(47);
    ExecutorService exec = Executors.newCachedThreadPool();
    PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<Runnable>();
    exec.execute(new PrioritizedTaskProducer(queue, exec));
    exec.execute(new PrioritizedTaskConsumer(queue));
}
 
Example 11
Project: think-in-java   File: NaiveExceptionHandling.java   View Source Code Vote up 5 votes
public static void main(String[] args)
{
	try
	{
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new ExceptionThread());
	} catch (RuntimeException ue)
	{
		// This statement will NOT execute!
		System.out.println("Exception has been handled!");
	}
}
 
Example 12
Project: think-in-java   File: ThreadLocalVariableHolder.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception
{
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++)
    {
        exec.execute(new Accessor(i));
    }
    TimeUnit.SECONDS.sleep(3); // Run for a while
    exec.shutdownNow(); // All Accessors will quit
}
 
Example 13
Project: elasticsearch_my   File: MockTcpTransport.java   View Source Code Vote up 5 votes
public MockTcpTransport(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                        CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
                        NetworkService networkService, Version mockVersion) {
    super("mock-tcp-transport", settings, threadPool, bigArrays, circuitBreakerService, namedWriteableRegistry, networkService);
    // we have our own crazy cached threadpool this one is not bounded at all...
    // using the ES thread factory here is crucial for tests otherwise disruption tests won't block that thread
    executor = Executors.newCachedThreadPool(EsExecutors.daemonThreadFactory(settings, Transports.TEST_MOCK_TRANSPORT_THREAD_PREFIX));
    this.mockVersion = mockVersion;
}
 
Example 14
Project: Paper-Melody   File: RetrofitClient.java   View Source Code Vote up 5 votes
public static void updateBaseUrl(String baseUrl) {
    BASE_URL = baseUrl;
    Executor executor = Executors.newCachedThreadPool();
    final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonDateTypeAdapter()).create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .callbackExecutor(executor)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(OkHttpProvider.getInstance())
            .build();

    socialSystemAPI = retrofit.create(SocialSystemAPI.class);
}
 
Example 15
Project: iotplatform   File: BaseAlarmService.java   View Source Code Vote up 4 votes
@PostConstruct
public void startExecutor() {
    readResultsProcessingExecutor = Executors.newCachedThreadPool();
}
 
Example 16
Project: java-performance   File: App1Main.java   View Source Code Vote up 4 votes
@Bean("threadPool")
ExecutorService threadPool() {
    return Executors.newCachedThreadPool();
}
 
Example 17
Project: Hotspot-master-devp   File: Platform.java   View Source Code Vote up 4 votes
public Executor defaultCallbackExecutor()
{
    return Executors.newCachedThreadPool();
}
 
Example 18
Project: SmartChart   File: Platform.java   View Source Code Vote up 4 votes
public Executor defaultCallbackExecutor() {
    return Executors.newCachedThreadPool();
}
 
Example 19
Project: GitHub   File: BoxingExecutor.java   View Source Code Vote up 4 votes
private void ensureWorkerHandlerNotNull() {
    if (mExecutorService == null) {
        mExecutorService = Executors.newCachedThreadPool();
    }
}
 
Example 20
Project: android-project-gallery   File: AsyncHttpClient.java   View Source Code Vote up 2 votes
/**
 * Get the default threading pool to be used for this HTTP client.
 *
 * @return The default threading pool to be used
 */
protected ExecutorService getDefaultThreadPool() {
    return Executors.newCachedThreadPool();
}