Tabnine Logo
Executor
Code IndexAdd Tabnine to your IDE (free)

How to use
Executor
in
java.util.concurrent

Best Java code snippets using java.util.concurrent.Executor (Showing top 20 results out of 59,247)

Refine searchRefine arrow

  • Executors
  • ExecutorService
  • CountDownLatch
  • Random
origin: stackoverflow.com

 CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
 taskExecutor.execute(new MyTask());
}

try {
 latch.await();
} catch (InterruptedException E) {
  // handle
}
origin: stackoverflow.com

private final ExecutorService executor = Executors.newCachedThreadPool();
 private final Random random = new Random();
   this.map.remove("key" + random.nextInt(MAP_SIZE));
   this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
   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

private static final Random rand = new Random();
private Queue<JLabel> labels = new LinkedList<JLabel>();
private JPanel panel = new JPanel(new GridLayout(0, 1));
  public void actionPerformed(ActionEvent e) {
      startButton.setEnabled(false);
      CountDownLatch latch = new CountDownLatch(N);
      ExecutorService executor = Executors.newFixedThreadPool(N);
      for (JLabel label : labels) {
        label.setBackground(Color.white);
        executor.execute(new Counter(label, latch));
    latch.await();
    return null;
    int latency = rand.nextInt(42) + 10;
    for (int i = 1; i <= 100; i++) {
      publish(i);
  protected void done() {
    label.setBackground(Color.green);
    latch.countDown();
origin: stackoverflow.com

 ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
 taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
 taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
 ...
}
origin: stackoverflow.com

 import java.util.concurrent.*;
class ThreadIdTest {

 public static void main(String[] args) {

  final int numThreads = 5;
  ExecutorService exec = Executors.newFixedThreadPool(numThreads);

  for (int i=0; i<10; i++) {
   exec.execute(new Runnable() {
    public void run() {
     long threadId = Thread.currentThread().getId();
     System.out.println("I am thread " + threadId + " of " + numThreads);
    }
   });
  }

  exec.shutdown();
 }
}
origin: spring-projects/spring-integration

@Test
public void testSendInAnotherThread() throws Exception {
  simpleChannel.send(new GenericMessage<String>("test"));
  Executor otherThreadExecutor = Executors.newSingleThreadExecutor();
  final CountDownLatch latch = new CountDownLatch(1);
  otherThreadExecutor.execute(() -> {
    simpleChannel.send(new GenericMessage<String>("crap"));
    latch.countDown();
  });
  assertTrue(latch.await(10, TimeUnit.SECONDS));
  assertEquals("test", simpleChannel.receive(10).getPayload());
  // Message sent on another thread is not collected here
  assertEquals(null, simpleChannel.receive(10));
}
origin: stackoverflow.com

public void start(Stage primaryStage) {
 TableView<TestTask> table = new TableView<TestTask>();
 Random rng = new Random();
 for (int i = 0; i < 20; i++) {
  table.getItems().add(
    new TestTask(rng.nextInt(3000) + 2000, rng.nextInt(30) + 20));
 primaryStage.show();
 ExecutorService executor = Executors.newFixedThreadPool(table.getItems().size(), new ThreadFactory() {
  @Override
  public Thread newThread(Runnable r) {
  executor.execute(task);
origin: serso/android-checkout

final AtomicInteger counter = new AtomicInteger();
final AtomicInteger expected = new AtomicInteger();
final Random r = new Random(System.currentTimeMillis());
final ListUncaughtExceptionHandler eh = new ListUncaughtExceptionHandler();
final Executor executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
  @Override
  public Thread newThread(Runnable r) {
  switch (r.nextInt(4)) {
    case 0:
      expected.incrementAndGet();
      requests.add(newRequest(i + 1, counter, r.nextInt(20)));
      executor.execute(requests);
      break;
    case 1:
  executor.execute(requests);
  Thread.sleep(50);
origin: androidannotations/androidannotations

if (executor instanceof ExecutorService) {
  ExecutorService executorService = (ExecutorService) executor;
  future = executorService.submit(runnable);
} else {
  executor.execute(runnable);
origin: stackoverflow.com

private final Random random = new Random();
private final ExecutorService exec = Executors.newSingleThreadExecutor();
 exec.shutdownNow();
 exec.execute(swimTask);
 exec.execute(bikeTask);
 exec.execute(runTask);
   random.nextDouble() * (max - min) + min
  );
origin: voldemort/voldemort

@Test
public void testThreadOverload() throws Exception {
  final Store<ByteArray, byte[], byte[]> store = getStore();
  int numOps = 100;
  final CountDownLatch latch = new CountDownLatch(numOps);
  Executor exec = Executors.newCachedThreadPool();
  for(int i = 0; i < numOps; i++) {
    exec.execute(new Runnable() {
      public void run() {
        store.put(TestUtils.toByteArray(TestUtils.randomString("abcdefghijklmnopqrs",
                                    10)),
             new Versioned<byte[]>(TestUtils.randomBytes(8)),
             null);
        latch.countDown();
      }
    });
  }
  latch.await();
}
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: stackoverflow.com

 final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
ExecutorService ex = Executors.newFixedThreadPool(1000);
for (;;) {
  ex.execute(new Runnable() {
    public void run() {
      try {
        f.format(new Date(new Random().nextLong()));
      } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
      }
    };
  });
}
origin: serso/android-checkout

final OneThreadCache c = new OneThreadCache();
final ConcurrentCache cache = new ConcurrentCache(c);
final Executor executor = Executors.newFixedThreadPool(20);
final Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 100; i++) {
  executor.execute(new Runnable() {
    @Override
    public void run() {
origin: stackoverflow.com

 ExecutorService e = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// Do work using something like either
e.execute(new Runnable() {
    public void run() {
      // do one task
    }
  });
origin: io.netty/netty

public void execute(Runnable command) {
  if (command == null) {
    throw new NullPointerException("command");
  }
  if (shutdown) {
    throw new RejectedExecutionException();
  }
  if (s != null) {
    s.execute(new ChildExecutorRunnable(command));
  } else {
    e.execute(new ChildExecutorRunnable(command));
  }
}
origin: stackoverflow.com

 /* Get an executor service that will run a maximum of 5 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(5);
/* For all the 100 tasks to be done altogether... */
for (int i = 0; i < 100; i++) {
  /* ...execute the task to run concurrently as a runnable: */
  exec.execute(new Runnable() {
    public void run() {
      /* do the work to be done in its own thread */
      System.out.println("Running in: " + Thread.currentThread());
    }
  });
}
/* Tell the executor that after these 100 steps above, we will be done: */
exec.shutdown();
try {
  /* The tasks are now running concurrently. We wait until all work is done, 
   * with a timeout of 50 seconds: */
  boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
  /* If the execution timed out, false is returned: */
  System.out.println("All done: " + b);
} catch (InterruptedException e) { e.printStackTrace(); }
origin: square/retrofit

 @Override public void onFailure(Call<T> call, final Throwable t) {
  callbackExecutor.execute(new Runnable() {
   @Override public void run() {
    callback.onFailure(ExecutorCallbackCall.this, t);
   }
  });
 }
});
origin: stackoverflow.com

 ExecutorService exec = Executors.newFixedThreadPool(4,
    new ThreadFactory() {
      public Thread newThread(Runnable r) {
        Thread t = Executors.defaultThreadFactory().newThread(r);
        t.setDaemon(true);
        return t;
      }
    });

exec.execute(YourTaskNowWillBeDaemon);
origin: stackoverflow.com

int nThreads = 100;
 ExecutorService ex = Executors.newFixedThreadPool(nThreads);
 for (int i = 0; i < nThreads; i++) {
   ex.execute(new Walker());
 }
 Thread.sleep(5000);
 ex.shutdownNow();
java.util.concurrentExecutor

Javadoc

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
 
Executor executor = anExecutor; 
executor.execute(new RunnableTask1()); 
executor.execute(new RunnableTask2()); 
... 
However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:
 
class DirectExecutor implements Executor { 
public void execute(Runnable r) { 
r.run(); 
} 
}
More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.
 
class ThreadPerTaskExecutor implements Executor { 
public void execute(Runnable r) { 
new Thread(r).start(); 
} 
}
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.
  
class SerialExecutor implements Executor public synchronized void execute(final Runnable r)  
tasks.offer(new Runnable()  
public void run()  
try  
r.run(); 
} finally  
scheduleNext(); 
} 
} 
}); 
if (active == null)  
scheduleNext(); 
} 
} 
protected synchronized void scheduleNext()  
if ((active = tasks.poll()) != null)  
executor.execute(active); 
} 
} 
}}
The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executorhappen-before its execution begins, perhaps in another thread.

Most used methods

  • execute
    Executes the given command at some time in the future. The command may execute in a new thread, in a
  • <init>

Popular in Java

  • Making http post requests using okhttp
  • getSystemService (Context)
  • onRequestPermissionsResult (Fragment)
  • runOnUiThread (Activity)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • FileNotFoundException (java.io)
    Thrown when a file specified by a program cannot be found.
  • NoSuchElementException (java.util)
    Thrown when trying to retrieve an element past the end of an Enumeration or Iterator.
  • Vector (java.util)
    Vector is an implementation of List, backed by an array and synchronized. All optional operations in
  • Handler (java.util.logging)
    A Handler object accepts a logging request and exports the desired messages to a target, for example
  • Project (org.apache.tools.ant)
    Central representation of an Ant project. This class defines an Ant project with all of its targets,
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

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