canonical example by Tabnine
public void runThreadTask() { ExecutorService service = Executors.newCachedThreadPool(); service.execute( () -> { // ... do something inside runnable task }); service.shutdown(); }
ExecutorService es = Executors.newCachedThreadPool(); es.execute(new ThreadA());
public void run(long forHowLong, TimeUnit unit) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); pool.submit(producer); pool.submit(consumer); pool.submit(consumer); pool.shutdown(); pool.awaitTermination(forHowLong, unit); }
ExecutorService es = Executors.newCachedThreadPool(); for(int i=0;i<5;i++) es.execute(new Runnable() { /* your task */ }); es.shutdown(); boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES); // all tasks have finished or the time has been reached.
public static void usingCachedThreadPool() { System.out.println("=== CachedThreadPool ==="); ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); List<Future<UUID>> uuids = new LinkedList<>(); for (int i = 0; i < 10; i++) { Future<UUID> submitted = cachedThreadPool.submit(() -> { UUID randomUUID = UUID.randomUUID(); System.out.println("UUID " + randomUUID + " from " + Thread.currentThread().getName()); return randomUUID; }); uuids.add(submitted); } cachedThreadPool.execute(() -> uuids.forEach((f) -> { try { System.out.println("Result " + f.get() + " from thread " + Thread.currentThread().getName()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } })); cachedThreadPool.shutdown(); try { cachedThreadPool.awaitTermination(4, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("\n\n"); }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); Runnable barrierAction = () -> System.out.println("Well done, guys!"); CyclicBarrier barrier = new CyclicBarrier(10, barrierAction); Runnable task = () -> { try { // simulating a task that can take at most 1sec to run System.out.println("Doing task for " + Thread.currentThread().getName()); Thread.sleep(new Random().nextInt(10) * 100); System.out.println("Done for " + Thread.currentThread().getName()); barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }; for (int i = 0; i < 10; i++) { executor.execute(task); } executor.shutdown(); }
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; } }
public void go() throws IOException { final ServerSocket s = new ServerSocket(listenPort); final ExecutorService exe = Executors.newCachedThreadPool(); while (true) { final Socket incoming = s.accept(); ip = incoming.getLocalAddress().getHostAddress(); System.out.println("New Client Connected from " + incoming.getInetAddress().getHostName() + "... "); exe.submit(new FtpLoop(incoming, this)); } }
private final ExecutorService executor = Executors.newCachedThreadPool(); System.out.println( Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']' ); System.out.println(Thread.currentThread().getName() + ": " + i); Mutator m = new Mutator(this.map); executor.execute(a1); executor.execute(m); executor.execute(a2);
ExecutorService executor = Executors.newCachedThreadPool(); Callable<Object> task = new Callable<Object>() { public Object call() { return something.blockingMethod(); } }; Future<Object> future = executor.submit(task); try { Object result = future.get(5, TimeUnit.SECONDS); } catch (TimeoutException ex) { // handle the timeout } catch (InterruptedException e) { // handle the interrupts } catch (ExecutionException e) { // handle other exceptions } finally { future.cancel(true); // may or may not desire this }
public static String execAndReturn(String[] cmd) { ExecutorService executor = Executors.newCachedThreadPool(); try { ProcessBuilder builder = new ProcessBuilder(cmd); builder.redirectErrorStream(true); Process process = builder.start(); StreamCollector collector = new StreamCollector(process.getInputStream()); executor.execute(collector); process.waitFor(); if (! executor.awaitTermination(15, TimeUnit.SECONDS)) { executor.shutdownNow(); if (! executor.awaitTermination(5, TimeUnit.SECONDS)) { System.err.println("Stream collector did not terminate."); } } return collector.get(); } catch (IOException | InterruptedException e) { return null; } }
ExecutorService pool = Executors.newCachedThreadPool(); for(int i = 0; i < myList.size(); ++i) { pool.execute (new ThreadProcessRunnable (args)); } pool.shutdown(); pool.awaitTermination();//blocks the main thread System.out.println("last thread should execute this");
throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); exec.shutdown(); exec.awaitTermination(500, TimeUnit.MILLISECONDS);
@Test void shouldBeConsistentAfterConcurrentWritesAndCrashes() throws Exception ExecutorService executorService = Executors.newCachedThreadPool(); try ( EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction() ) for ( Future<Void> future : futures ) future.get(); executorService.shutdown();
throws TimeoutException, ExecutionException { long endMs = System.currentTimeMillis() + timeoutMs; ExecutorService service = Executors.newCachedThreadPool(); try { List<Future<T>> pending = new ArrayList<>(); for (Callable<T> c : callables) { pending.add(service.submit(c)); future.get(); } catch (InterruptedException e) {
public static void main(String[] args) { Runnable r = new Runnable() { public void run() { runYourBackgroundTaskHere(); } }; ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(r); //this line will execute immediately, not waiting for your task to complete }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); UsingExplicitReadWriteLocks uerwl = new UsingExplicitReadWriteLocks(); // Readers for (int i = 0; i < 100; i++) { executor.submit(() -> { try { // Delay readers to start Thread.sleep(new Random().nextInt(10) * 100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(uerwl.showContent()); }); } // Writers - only if no writer is available for (int i = 0; i < 5; i++) { executor.execute(() -> uerwl.writeContent(UUID.randomUUID().toString())); } executor.shutdown(); }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(3); Runnable r = () -> { try { Thread.sleep(1000); System.out.println("Service in " + Thread.currentThread().getName() + " initialized."); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; executor.execute(r); executor.execute(r); executor.execute(r); try { latch.await(2, TimeUnit.SECONDS); System.out.println("All services up and running!"); } catch (InterruptedException e) { e.printStackTrace(); } executor.shutdown(); }
server.setExecutor(Executors.newCachedThreadPool()); server.start(); System.out.println("Server is listening on port 8080" );
private int bkFence(final BookKeeperClient bkc, List<Long> ledgers, int fenceRate) throws Exception { if (ledgers.isEmpty()) { System.out.println("Nothing to fence. Done."); return 0; ExecutorService executorService = Executors.newCachedThreadPool(); final RateLimiter rateLimiter = RateLimiter.create(fenceRate); final byte[] passwd = getConf().getBKDigestPW().getBytes(UTF_8); executorService.submit(new Runnable() { @Override public void run() {