Java Thread Callable runConcurrently(final Callable task)

Here you can find the source of runConcurrently(final Callable task)

Description

Run the task concurrently 100 times.

License

Open Source License

Declaration

public static void runConcurrently(final Callable<Void> task) throws Exception 

Method Source Code

//package com.java2s;

import java.util.ArrayList;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    /**//from   w  w  w .j  av  a2  s  . c o m
     * Runs a task concurrently. Allows to test thread-safe behavior.
     *
     * @param task a {@link Callable} to run concurrently.
     * @throws Exception if any of the executed tasks fails.
     */
    public static void runConcurrently(final Callable<Void> task, final int times) throws Exception {
        final ExecutorService service = Executors.newFixedThreadPool(5);
        final List<Future<?>> futures = new ArrayList<Future<?>>();
        for (int i = 0; i < times; i++) {
            futures.add(service.submit(task));
        }
        for (final Future<?> future : futures) {
            future.get();
        }
    }

    /**
     * Run the task concurrently 100 times.
     */
    public static void runConcurrently(final Callable<Void> task) throws Exception {
        runConcurrently(task, 100);
    }
}

Related

  1. powerTo(final double base, final double[] exponents)
  2. repeatedlyTry(Callable task, int maxRounds, long backoff)
  3. resolveCompositeKey(final String key, final Map props)
  4. resolveSingle(Object object)
  5. runAndRethrowRuntimeExceptionOnFailure(final Callable operation, final String exceptionMessage)
  6. runConcurrently(final Callable task)
  7. runConcurrently(final Callable task, final int times)
  8. runInBackground(final Callable callable)
  9. runTest(Callable test)