Tabnine Logo
Executors.newCachedThreadPool
Code IndexAdd Tabnine to your IDE (free)

How to use
newCachedThreadPool
method
in
java.util.concurrent.Executors

Best Java code snippets using java.util.concurrent.Executors.newCachedThreadPool (Showing top 20 results out of 13,572)

Refine searchRefine arrow

  • ExecutorService.submit
  • ExecutorService.shutdown
  • PrintStream.println
  • Future.get
  • Executor.execute
canonical example by Tabnine

public void runThreadTask() {
 ExecutorService service = Executors.newCachedThreadPool();
 service.execute(
   () -> {
    // ... do something inside runnable task
   });
 service.shutdown();
}
origin: stackoverflow.com

 ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());
origin: LeonardoZ/java-concurrency-patterns

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);
}
origin: stackoverflow.com

 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.
origin: LeonardoZ/java-concurrency-patterns

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");
}
origin: LeonardoZ/java-concurrency-patterns

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();
}
origin: frohoff/ysoserial

  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;
  }
}
origin: plantuml/plantuml

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));
  }
}
origin: stackoverflow.com

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);
origin: stackoverflow.com

 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
}
origin: iBotPeaches/Apktool

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;
  }
}
origin: stackoverflow.com

 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");
origin: google/guava

 throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newCachedThreadPool();
exec.shutdown();
exec.awaitTermination(500, TimeUnit.MILLISECONDS);
origin: neo4j/neo4j

@Test
void shouldBeConsistentAfterConcurrentWritesAndCrashes() throws Exception
  ExecutorService executorService = Executors.newCachedThreadPool();
  try ( EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction() )
      for ( Future<Void> future : futures )
        future.get();
    executorService.shutdown();
origin: Alluxio/alluxio

 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) {
origin: stackoverflow.com

 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
}
origin: LeonardoZ/java-concurrency-patterns

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();
}
origin: LeonardoZ/java-concurrency-patterns

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();
}
origin: stackoverflow.com

server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
origin: twitter/distributedlog

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() {
java.util.concurrentExecutorsnewCachedThreadPool

Javadoc

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

Popular methods of Executors

  • newFixedThreadPool
    Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue,
  • newSingleThreadExecutor
    Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the
  • newSingleThreadScheduledExecutor
    Creates a single-threaded executor that can schedule commands to run after a given delay, or to exec
  • newScheduledThreadPool
    Creates a thread pool that can schedule commands to run after a given delay, or to execute periodica
  • defaultThreadFactory
    Returns a default thread factory used to create new threads. This factory creates all new threads us
  • callable
    Returns a Callable object that, when called, runs the given privileged exception action and returns
  • unconfigurableScheduledExecutorService
    Returns an object that delegates all defined ScheduledExecutorService methods to the given executor,
  • unconfigurableExecutorService
    Returns an object that delegates all defined ExecutorService methods to the given executor, but not
  • newWorkStealingPool
    Creates a thread pool that maintains enough threads to support the given parallelism level, and may
  • privilegedThreadFactory
    Legacy security code; do not use.
  • privilegedCallable
    Legacy security code; do not use.
  • privilegedCallableUsingCurrentClassLoader
    Legacy security code; do not use.
  • privilegedCallable,
  • privilegedCallableUsingCurrentClassLoader

Popular in Java

  • Making http post requests using okhttp
  • getExternalFilesDir (Context)
  • onRequestPermissionsResult (Fragment)
  • addToBackStack (FragmentTransaction)
  • Point (java.awt)
    A point representing a location in (x,y) coordinate space, specified in integer precision.
  • List (java.util)
    An ordered collection (also known as a sequence). The user of this interface has precise control ove
  • Handler (java.util.logging)
    A Handler object accepts a logging request and exports the desired messages to a target, for example
  • JFrame (javax.swing)
  • JPanel (javax.swing)
  • Get (org.apache.hadoop.hbase.client)
    Used to perform Get operations on a single row. To get everything for a row, instantiate a Get objec
  • Top 17 Free Sublime Text Plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now