Package java.util.concurrent

Examples of java.util.concurrent.ExecutorService


    }

    public static int[][] parallelMult(ArrayList<ArrayList<Integer>> A,
            ArrayList<ArrayList<Integer>> B, int threadNumber) {
        int[][] C = new int[A.size()][B.get(0).size()];
        ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
        List<Future<int[][]>> list = new ArrayList<Future<int[][]>>();

        int part = A.size() / threadNumber;
        if (part < 1) {
            part = 1;
        }
        for (int i = 0; i < A.size(); i += part) {
            System.err.println(i);
            Callable<int[][]> worker = new LineMultiplier(A, B, i, i+part);
            Future<int[][]> submit = executor.submit(worker);
            list.add(submit);
        }

        // now retrieve the result
        int start = 0;
        int CF[][];
        for (Future<int[][]> future : list) {
            try {
                CF = future.get();
                for (int i=start; i < start+part; i += 1) {
                    C[i] = CF[i];
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            start+=part;
        }
        executor.shutdown();

        return C;
    }
View Full Code Here


import java.util.concurrent.TimeoutException;

public class MultipleCorePrimeTest {
    public static void count(int target, int threads)
      throws InterruptedException, TimeoutException {
        ExecutorService executor =
            Executors.newFixedThreadPool(threads);
        List<FutureTask<Integer>> taskList =
            new ArrayList<FutureTask<Integer>>();
        long startTime = System.currentTimeMillis();

        for (int i = 1; i <= threads; ++i) {
            int ilen = target / threads;

            /* Test following intervall for primes */
            final int start = (i - 1) * ilen;
            final int end = (i != threads)
                            ? i * ilen - 1
                            : target;
            FutureTask<Integer> task =
                new FutureTask<Integer>(
                  new Callable<Integer>() {
                    @Override
                    public Integer call() {
                        int count = 0;
                        for (int i = start; i <= end;
                                            ++i) {
                            if (SingleCorePrimeTest.
                                  isPrime(i))
                                ++count;
                        }
                        return count;
                    }
                });
            taskList.add(task);
            executor.submit(task);
        }

        executor.shutdown();
        if (!executor.awaitTermination(10,
            TimeUnit.MINUTES)) {
                throw new TimeoutException();
        }
        final long endTime = System.currentTimeMillis();
        int count = 0;
View Full Code Here

    }
//    void call(int i) {}

    @Test
    public void test() {
        ExecutorService es = Executors.newCachedThreadPool();
        es.submit(this::call);
    }
View Full Code Here

        }
      }
    }

    // shut down all our thread pools
    ExecutorService toShutdown[] = {callTimeoutPool, timedRollerPool};
    for (ExecutorService execService : toShutdown) {
      execService.shutdown();
      try {
        while (execService.isTerminated() == false) {
          execService.awaitTermination(
View Full Code Here

    return this;
  }

  @Override
  public Future<?> start() {
    ExecutorService executor = Executors.newFixedThreadPool( 1, "batch coordinator" );
    try {
      return executor.submit( createCoordinator() );
    }
    finally {
      executor.shutdown();
    }
  }
View Full Code Here

   *
   * @throws InterruptedException
   *             if interrupted while waiting for endAllSignal.
   */
  private void doBatchWork(BatchBackend backend) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, "BatchIndexingWorkspace" );
    for ( Class<?> type : rootEntities ) {
      executor.execute( new BatchIndexingWorkspace( gridDialect, searchFactoryImplementor, sessionFactory, type,
          cacheMode, endAllSignal, monitor, backend ) );
    }
    executor.shutdown();
    endAllSignal.await(); // waits for the executor to finish
  }
View Full Code Here

    if(benchmarkInstances.isEmpty()){
      throw new IllegalStateException("no instance specified. at least one instance needs to be specified.");
    }
    System.out.println("start benchmarking [nuAlgorithms="+algorithms.size()+"][nuInstances=" + benchmarkInstances.size() + "][runsPerInstance=" + runs + "]");
    double startTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    for(final Algorithm algorithm : algorithms){
      for(final BenchmarkInstance p : benchmarkInstances){
        for(int run=0;run<runs;run++){
          final int r = run;
          executor.submit(new Runnable(){

            @Override
            public void run() {
              runAlgorithm(p, algorithm, r+1);
            }
           
          });
        }
      }
    }
    try {
      executor.shutdown();
      executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
     
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("benchmarking done [time="+(System.currentTimeMillis()-startTime)/1000 + "sec]");
View Full Code Here

      return this;
    }
  }

  public void testJitBindingFromAnotherThreadDuringInjection() {
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    final AtomicReference<JustInTime> got = new AtomicReference<JustInTime>();

    Guice.createInjector(new AbstractModule() {
      protected void configure() {
        requestInjection(new Object() {
          @Inject void initialize(final Injector injector)
              throws ExecutionException, InterruptedException {
            Future<JustInTime> future = executorService.submit(new Callable<JustInTime>() {
              public JustInTime call() throws Exception {
                return injector.getInstance(JustInTime.class);
              }
            });
            got.set(future.get());
View Full Code Here

    }
  }

  public void run() {
    // Have up to 5 URL requests running at a time
    ExecutorService es = Executors.newFixedThreadPool(5);

    while (isRunning) {

      try {

        List<ServiceWizardMapEntry> localIconsToRetrieve = null;

        synchronized (lock) {
          lock.wait(1000);

          if (isRunning && iconsToRetrieve.size() > 0) {

            localIconsToRetrieve = new ArrayList<ServiceWizardMapEntry>();
            localIconsToRetrieve.addAll(iconsToRetrieve);
            iconsToRetrieve.clear();
          }

        }

        if (isRunning && localIconsToRetrieve != null) {
          // Process icon requests outside the lock

          for (ServiceWizardMapEntry e : localIconsToRetrieve) {
            IconRetrieveRunnable r = new IconRetrieveRunnable(e);
            es.execute(r);
          }

          localIconsToRetrieve.clear();
        }

      }
      catch (InterruptedException e) {
        isRunning = false;
      }

    }

    es.shutdownNow();

    try {
      // Wait at most 10 seconds for the remaining tasks to finish
      es.awaitTermination(10, TimeUnit.SECONDS);
    }
    catch (InterruptedException e1) {
      // ignore.
    }
View Full Code Here

        final Log log = new Log(bundleContext);
        log.info("starting test_ConcurrentManagedServicesWithConcurrentConfigurations");
        // Use at least 10 parallel threads, or take all available processors if the running host contains more than 10 processors.
        int parallelism = Math.max(10, Runtime.getRuntime().availableProcessors());
        final ConfigurationAdmin ca = getConfigurationAdmin();
        final ExecutorService executor = Executors.newFixedThreadPool(parallelism);
        try
        {
            int pidCounter = 0;

            long timeStamp = System.currentTimeMillis();
            for (int loop = 0; loop < 1000; loop++)
            {
                log.debug("loop#%d -------------------------", (loop + 1));

                final CountDownLatch managedServiceUpdated = new CountDownLatch(MANAGED_SERVICES);
                final CountDownLatch managedServiceUnregistered = new CountDownLatch(MANAGED_SERVICES);

                // Create some ManagedServices concurrently
                log.info("registering aspects concurrently");
                final CopyOnWriteArrayList<ServiceRegistration> managedServices = new CopyOnWriteArrayList<ServiceRegistration>();
                final CopyOnWriteArrayList<Configuration> confs = new CopyOnWriteArrayList<Configuration>();

                for (int i = 0; i < MANAGED_SERVICES; i++)
                {
                    final String pid = "pid." + i + "-" + (pidCounter++);
                    executor.execute(new Runnable()
                    {
                        public void run()
                        {
                            Hashtable props = new Hashtable();
                            props.put(Constants.SERVICE_PID, pid);

                            ServiceRegistration sr = bundleContext.registerService(
                                ManagedService.class.getName(),
                                new TestManagedService(managedServiceUpdated), props);
                            managedServices.add(sr);
                            try
                            {
                                Configuration c = ca.getConfiguration(pid, null);
                                c.update(new Hashtable()
                                {
                                    {
                                        put("foo", "bar");
                                    }
                                });
                                confs.add(c);
                            }
                            catch (IOException e)
                            {
                                log.error("could not create pid %s", e, pid);
                                return;
                            }
                        }
                    });
                }

                if (!managedServiceUpdated.await(MAXWAIT, TimeUnit.MILLISECONDS))
                {
                    TestCase.fail("Detected errors logged during concurrent test");
                    break;
                }
                log.info("all managed services updated");

                // Unregister managed services concurrently
                log.info("unregistering services concurrently");
                for (final ServiceRegistration sr : managedServices)
                {
                    executor.execute(new Runnable()
                    {
                        public void run()
                        {
                            sr.unregister();
                            managedServiceUnregistered.countDown();
View Full Code Here

TOP

Related Classes of java.util.concurrent.ExecutorService

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.