示例#1
0
  @Test
  public void test() throws InterruptedException, ExecutionException {
    ExecutorService service = Executors.newFixedThreadPool(2);
    List<TimeConsumingCallable> list1 = Lists.newArrayList();
    List<TimeConsumingCallable> list2 = Lists.newArrayList();
    List<TimeConsumingCallable> list3 = Lists.newArrayList();
    List<Future<Integer>> futureList = Lists.newArrayList();

    for (int i = 0; i < 20; i++) {
      TimeConsumingCallable callable = new TimeConsumingCallable(i);
      list1.add(callable);
    }

    for (int i = 30; i < 55; i++) {
      TimeConsumingCallable callable = new TimeConsumingCallable(i);
      list2.add(callable);
    }

    for (int i = 60; i < 80; i++) {
      TimeConsumingCallable callable = new TimeConsumingCallable(i);
      list3.add(callable);
    }

    futureList.addAll(service.invokeAll(list1));
    futureList.addAll(service.invokeAll(list2));
    futureList.addAll(service.invokeAll(list3));

    for (Future<Integer> future : futureList) {
      Integer num = future.get();
      System.out.println(num);
      //            System.out.println("done");
    }
  }
 @Test
 public void testInvokeAllTimeoutCancelled() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testInvokeAll");
   assertFalse(executor.isShutdown());
   // Only one task
   ArrayList<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
   tasks.add(new CancellationAwareTask(0));
   List<Future<Boolean>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), 1);
   assertEquals(futures.get(0).get(), Boolean.TRUE);
   // More tasks
   tasks.clear();
   for (int i = 0; i < COUNT; i++) {
     tasks.add(new CancellationAwareTask(i < 2 ? 0 : 20000));
   }
   futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), COUNT);
   for (int i = 0; i < COUNT; i++) {
     if (i < 2) {
       assertEquals(futures.get(i).get(), Boolean.TRUE);
     } else {
       boolean excepted = false;
       try {
         futures.get(i).get();
       } catch (CancellationException e) {
         excepted = true;
       }
       assertTrue(excepted);
     }
   }
 }
  @Override
  public BxDocument segmentDocument(BxDocument document) throws AnalysisException {
    Map<BxPage, List<Component>> componentMap = new HashMap<BxPage, List<Component>>();

    ExecutorService exec = Executors.newFixedThreadPool(PdfNLMContentExtractor.THREADS_NUMBER);
    ArrayList<Callable<NumBxPage>> tasks = new ArrayList<Callable<NumBxPage>>();
    for (BxPage page : document.getPages()) {
      tasks.add(new ComponentCounter(page));
    }

    List<Future<NumBxPage>> results;
    try {
      results = exec.invokeAll(tasks);
      exec.shutdown();

      for (Future<NumBxPage> result : results) {
        NumBxPage p = result.get();
        componentMap.put(p.page, p.components);
      }
    } catch (ExecutionException ex) {
      throw new AnalysisException("Cannot segment pages!", ex);
    } catch (InterruptedException ex) {
      throw new AnalysisException("Cannot segment pages!", ex);
    }

    this.computeDocumentOrientation(componentMap);

    BxDocument output = new BxDocument();
    BxPage[] pages = new BxPage[document.getPages().size()];

    exec = Executors.newFixedThreadPool(PdfNLMContentExtractor.THREADS_NUMBER);
    tasks = new ArrayList<Callable<NumBxPage>>();
    int i = 0;
    for (BxPage page : document.getPages()) {
      tasks.add(new SingleSegmenter(page, i++));
    }

    try {
      results = exec.invokeAll(tasks);
      exec.shutdown();

      for (Future<NumBxPage> result : results) {
        NumBxPage p = result.get();
        pages[p.index] = p.page;
      }
      for (BxPage p : pages) {
        if (p.getBounds() != null) {
          output.addPage(p);
        }
      }
      return output;
    } catch (ExecutionException ex) {
      throw new AnalysisException("Cannot segment pages!", ex);
    } catch (InterruptedException ex) {
      throw new AnalysisException("Cannot segment pages!", ex);
    }
  }
  /**
   * 读取行情数据到Bean中。
   *
   * @param worker 驱动工作任务的线程池
   * @param marketDataFilepathMapList 装载市场行情数据文件路径的分割集合
   * @param startMonitorTask 是否启动监听线程
   * @param currentReadMarketDataNum 当前已经载入的股票行情数据的个数
   * @return List<MarketDataBean>
   * @throws InterruptedException
   * @throws ExecutionException
   */
  private List<MarketDataBean> readMarketDataToBean(
      ExecutorService worker,
      List<Map<String, String>> marketDataFilepathMapList,
      boolean startMonitorTask,
      AtomicInteger currentReadMarketDataNum)
      throws InterruptedException, ExecutionException {

    // 根据装载市场数据文件路径集合的尺寸,创建同样多个装载数据的任务类。
    List<DataLoadTask> dataLoadTaskList =
        getDataLoadTaskList(marketDataFilepathMapList, startMonitorTask, currentReadMarketDataNum);

    // 使用线程池驱动任务。
    List<Future<List<MarketDataBean>>> futureList = worker.invokeAll(dataLoadTaskList);
    worker.shutdown();

    List<MarketDataBean> marketDataList = new CopyOnWriteArrayList<MarketDataBean>();

    if (null != futureList && !futureList.isEmpty()) {
      for (Future<List<MarketDataBean>> future : futureList) {
        for (MarketDataBean marketData : future.get()) {
          marketDataList.add(marketData);
        }
      }
    }

    return marketDataList;
  }
 private long goNextTick() {
   // TODO optimize this method to skip ticks until the next tick with
   // scheduled tasks is found
   Set<FrameworkTask> set = taskQueue.get(++currentTick);
   taskQueue.remove(currentTick);
   logger.log(Level.FINEST, "Tick {0} executed", currentTick);
   if (set != null) {
     try {
       decayModules();
       executorService.invokeAll(set); // Execute all tasks scheduled
       // for this tick
     } catch (InterruptedException e) {
       if (!shuttingDown) {
         logger.log(
             Level.WARNING,
             "Current tick {0} was interrupted because of {1}",
             new Object[] {currentTick, e.getMessage()});
       } else {
         logger.log(
             Level.INFO, "Current tick {0} interrupted for application shutdown.", currentTick);
       }
     }
   }
   return currentTick;
 }
  protected static void execute(
      Collection<Callable<Void>> callables,
      AtomicInteger noEstimateCounter,
      RunningAverageAndStdDev timing)
      throws TasteException {

    Collection<Callable<Void>> wrappedCallables =
        wrapWithStatsCallables(callables, noEstimateCounter, timing);
    int numProcessors = Runtime.getRuntime().availableProcessors();
    ExecutorService executor = Executors.newFixedThreadPool(numProcessors);
    /*int numProcessors = 50; GAE
    ThreadFactory tf = ThreadManager.currentRequestThreadFactory();
    ExecutorService executor = Executors.newCachedThreadPool(tf);*/
    log.info("Starting timing of {} tasks in {} threads", wrappedCallables.size(), numProcessors);
    try {
      List<Future<Void>> futures = executor.invokeAll(wrappedCallables);
      // Go look for exceptions here, really
      for (Future<Void> future : futures) {
        future.get();
      }

    } catch (InterruptedException ie) {
      throw new TasteException(ie);
    } catch (ExecutionException ee) {
      throw new TasteException(ee.getCause());
    }

    executor.shutdown();
    try {
      executor.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      throw new TasteException(e.getCause());
    }
  }
 /** Shut down the cluster, including all Solr nodes and ZooKeeper */
 public void shutdown() throws Exception {
   try {
     if (solrClient != null) solrClient.close();
     List<Callable<JettySolrRunner>> shutdowns = new ArrayList<>(jettys.size());
     for (final JettySolrRunner jetty : jettys) {
       shutdowns.add(() -> stopJettySolrRunner(jetty));
     }
     jettys.clear();
     Collection<Future<JettySolrRunner>> futures = executor.invokeAll(shutdowns);
     Exception shutdownError =
         checkForExceptions("Error shutting down MiniSolrCloudCluster", futures);
     if (shutdownError != null) {
       throw shutdownError;
     }
   } finally {
     executor.shutdown();
     executor.awaitTermination(2, TimeUnit.SECONDS);
     try {
       if (!externalZkServer) {
         zkServer.shutdown();
       }
     } finally {
       System.clearProperty("zkHost");
     }
   }
 }
 private void testConcurrency(final CollectionHolder<List<Integer>> holder)
     throws InterruptedException, ExecutionException {
   final List<Integer> list = holder.collection;
   // make a big array that takes a long time to toString()
   list.addAll(LIST);
   // Create a thread pool with two threads to cause the most contention on the underlying
   // resource.
   final ExecutorService threadPool = Executors.newFixedThreadPool(2);
   // Consumes toStrings
   Callable<Integer> consumer =
       new Callable<Integer>() {
         public Integer call() {
           for (int i = 0; i < REPEAT; i++) {
             // Calls ToStringStyle
             new ToStringBuilder(holder).append(holder.collection);
           }
           return REPEAT;
         }
       };
   Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
   tasks.add(consumer);
   tasks.add(consumer);
   final List<Future<Integer>> futures = threadPool.invokeAll(tasks);
   for (Future<Integer> future : futures) {
     future.get();
   }
 }
示例#9
0
  void mediate(int subtasks) throws InterruptedException, ExecutionException {

    ExecutorService executorService = Executors.newFixedThreadPool(subtasks * 2);

    List<Callable<StringPair>> tasks = Lists.newArrayList();
    Broker<String> broker = new Broker<String>();

    for (int subtask = 0; subtask < subtasks; subtask++) {
      tasks.add(new IterationHead(broker, subtask, "value" + subtask));
      tasks.add(new IterationTail(broker, subtask));
    }

    Collections.shuffle(tasks);

    int numSuccessfulHandovers = 0;
    for (Future<StringPair> future : executorService.invokeAll(tasks)) {
      StringPair stringPair = future.get();
      if (stringPair != null) {
        assertEquals("value" + stringPair.getFirst(), stringPair.getSecond());
        numSuccessfulHandovers++;
      }
    }

    assertEquals(subtasks, numSuccessfulHandovers);
  }
示例#10
0
  @Test
  public void testNetty2978Concurrent() throws Exception {
    final CamelClient client = new CamelClient();
    try {
      final List<Callable<String>> callables = new ArrayList<Callable<String>>();
      for (int count = 0; count < 1000; count++) {
        final int i = count;
        callables.add(
            new Callable<String>() {
              public String call() {
                return client.lookup(i);
              }
            });
      }

      final ExecutorService executorService = Executors.newFixedThreadPool(10);
      final List<Future<String>> results = executorService.invokeAll(callables);
      final Set<String> replies = new HashSet<String>();
      for (Future<String> future : results) {
        // wait at most 60 sec to not hang test
        String reply = future.get(60, TimeUnit.SECONDS);
        assertTrue(reply.startsWith("Bye "));
        replies.add(reply);
      }

      // should be 1000 unique replies
      assertEquals(1000, replies.size());
      executorService.shutdownNow();
    } finally {
      client.close();
    }
  }
示例#11
0
  /**
   * Execute the {@link Callable} tasks in parallel (per the configured size of the {@link
   * WorkerPool}) and wait for them to complete.
   *
   * @param tasks a map of {@link Callable}s with keys by which you will be able to access each
   *     return value
   * @return the return values of each {@link Callable}s mapped by their input key
   */
  public <K, V> Map<K, V> invokeAll(Map<K, Callable<V>> tasks) {
    String caller =
        LOGGER.isDebugEnabled() ? Thread.currentThread().getStackTrace()[2].toString() : "n/a";
    LOGGER.debug("[%s] is invoking %d mapped tasks", caller, tasks.size());

    List<K> orderedKeys = new ArrayList<K>(tasks.size());
    List<Callable<V>> orderedTasks = new ArrayList<Callable<V>>(tasks.size());
    for (Map.Entry<K, Callable<V>> entry : tasks.entrySet()) {
      orderedKeys.add(entry.getKey());
      orderedTasks.add(entry.getValue());
    }

    try {
      long start = System.currentTimeMillis();
      List<Future<V>> executorResults = executorService.invokeAll(orderedTasks);
      long finish = System.currentTimeMillis();
      LOGGER.debug("[%s] invoked %d mapped tasks in %d ms", caller, tasks.size(), finish - start);

      Map<K, V> mappedResults = new LinkedHashMap<K, V>(tasks.size());
      for (int i = 0; i < tasks.size(); i++) {
        K key = orderedKeys.get(i);
        V result = executorResults.get(i).get();
        mappedResults.put(key, result);
      }
      return mappedResults;
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } catch (ExecutionException e) {
      throw new RuntimeException(e);
    }
  }
示例#12
0
  /**
   * We will test this by setting up two threads, asserting on the hash values the instances
   * generate for each thread
   *
   * @throws InterruptedException
   * @throws ExecutionException
   */
  @Test
  public void test_001_concurrent_match() throws InterruptedException, ExecutionException {

    // Setup callable method that reports the hashcode for the thread
    int threadCount = 2;
    Callable<Integer> task =
        new Callable<Integer>() {
          @Override
          public Integer call() {
            return Match.getInstance().hashCode();
          }
        };

    // Create n tasks to execute
    List<Callable<Integer>> tasks = Collections.nCopies(threadCount, task);

    // Execute the task for both tasks
    ExecutorService es = Executors.newFixedThreadPool(threadCount);
    List<Future<Integer>> futures = es.invokeAll(tasks);
    int hash1 = futures.get(0).get();
    int hash2 = futures.get(1).get();

    // The two hashcodes must NOT be equal
    Assert.assertThat(hash1, not(equalTo(hash2)));
  }
示例#13
0
  public List<TravelQuote> getRankedTravelQuotes(
      TravelInfo travelInfo,
      Set<TravelCompany> companies,
      Comparator<TravelQuote> ranking,
      long time,
      TimeUnit unit)
      throws InterruptedException {
    List<QuoteTask> tasks = new ArrayList<QuoteTask>();
    for (TravelCompany company : companies) tasks.add(new QuoteTask(company, travelInfo));

    List<Future<TravelQuote>> futures = exec.invokeAll(tasks, time, unit);

    List<TravelQuote> quotes = new ArrayList<TravelQuote>(tasks.size());
    Iterator<QuoteTask> taskIter = tasks.iterator();
    for (Future<TravelQuote> f : futures) {
      QuoteTask task = taskIter.next();
      try {
        quotes.add(f.get());
      } catch (ExecutionException e) {
        quotes.add(task.getFailureQuote(e.getCause()));
      } catch (CancellationException e) {
        quotes.add(task.getTimeoutQuote(e));
      }
    }

    Collections.sort(quotes, ranking);
    return quotes;
  }
  /**
   * Create and run testing thread(s)
   *
   * @param threadCount
   * @throws InterruptedException
   * @throws ExecutionException
   */
  private void testThread(final int threadCount) throws InterruptedException, ExecutionException {
    ProcessingResult pr = new ProcessingResult();
    NumericPairDataProcessor nm = new NumericPairDataProcessor();

    List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
    for (int i = 0; i < threadCount; i++) {
      // new set of wrong data(alphabetic instead of numeric to generate errors)
      // for each thread but same NumericPairDataProcessor and ProcessingResult
      final NumPairJob npt =
          new NumPairJob(
              nm, pr, newRandomDataList(NUMBER_OF_DATA, 7), newRandomDataList(NUMBER_OF_DATA, 6));
      Callable<Integer> task =
          new Callable<Integer>() {
            @Override
            public Integer call() {
              npt.run();
              return npt.pr.getErrorList().size();
            }
          };
      tasks.add(task);
    }

    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    // call all threads and wait for completion
    List<Future<Integer>> futures = executorService.invokeAll(tasks);

    // Validate
    Assert.assertEquals(futures.size(), threadCount);
    // x2 because they are numeric pairs
    Assert.assertEquals(NUMBER_OF_DATA * threadCount * 2, pr.getErrorList().size());
  }
 /** Run the command from an executor */
 private void runExecutor() {
   // Unlock Mode Codec
   try {
     session.getDataConn().getDataNetworkHandler().unlockModeCodec();
   } catch (FtpNoConnectionException e) {
     setTransferAbortedFromInternal(false);
     return;
   }
   // Run the command
   if (executorService == null) {
     executorService = Executors.newSingleThreadExecutor();
   }
   endOfCommand = new WaarpFuture(true);
   final ArrayList<Callable<Object>> tasks = new ArrayList<Callable<Object>>(1);
   tasks.add(Executors.callable(new FtpTransferExecutor(session, executingCommand)));
   try {
     executorService.invokeAll(tasks);
   } catch (InterruptedException e1) {
   }
   // XXX TRY FIX TO IMPROVE
   /*
   executorService.execute(new FtpTransferExecutor(session,
   	executingCommand));
   	*/
   try {
     commandFinishing.await();
   } catch (InterruptedException e) {
   }
 }
示例#16
0
  public DataFES fillVector(F2SF params, Instances is, int inst, DataFES d, Cluster cluster)
      throws InterruptedException {

    long ts = System.nanoTime();

    if (executerService.isShutdown())
      executerService = java.util.concurrent.Executors.newCachedThreadPool();

    final int length = is.length(inst);
    if (d == null || d.len < length)
      d = new DataFES(length, mf.getFeatureCounter().get(PipeGen.REL).shortValue());

    ArrayList<ParallelExtract> pe = new ArrayList<ParallelExtract>();
    for (int i = 0; i < Parser.THREADS; i++)
      pe.add(new ParallelExtract(extractor[i], is, inst, d, (F2SF) params.clone(), cluster));

    for (int w1 = 0; w1 < length; w1++) {
      for (int w2 = w1 + 1; w2 < length; w2++) {

        if (w1 == w2) continue;

        ParallelExtract.add(w1, w2);
      }
    }
    //		for(int i=0;i<efp.length;i++) efp[i].start();
    //		for(int i=0;i<efp.length;i++) efp[i].join();
    executerService.invokeAll(pe);

    timeExtract += (System.nanoTime() - ts);

    return d;
  }
示例#17
0
 /** invokeAll(empty collection) returns empty collection */
 public void testInvokeAll2() throws InterruptedException {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
     assertTrue(r.isEmpty());
   }
 }
  @Override
  public void executeTest() throws Exception {

    ODatabaseDocumentTx database =
        poolFactory.get(getDatabaseURL(serverInstance.get(0)), "admin", "admin").acquire();
    System.out.println("Creating Writers and Readers threads...");

    final ExecutorService writerExecutors = Executors.newCachedThreadPool();

    runningWriters = new CountDownLatch(serverInstance.size() * writerCount);

    int serverId = 0;
    int threadId = 0;
    List<Callable<Void>> writerWorkers = new ArrayList<Callable<Void>>();
    for (ServerRun server : serverInstance) {
      for (int j = 0; j < writerCount; j++) {
        Callable writer = createWriter(serverId, threadId++, getDatabaseURL(server));
        writerWorkers.add(writer);
      }
      serverId++;
    }
    List<Future<Void>> futures = writerExecutors.invokeAll(writerWorkers);

    System.out.println("Threads started, waiting for the end");

    for (Future<Void> future : futures) {
      future.get();
    }

    writerExecutors.shutdown();
    Assert.assertTrue(writerExecutors.awaitTermination(1, TimeUnit.MINUTES));

    System.out.println("All writer threads have finished, shutting down readers");
  }
  /**
   * Performs a very simple stress test using a pooling {@link Controller}. The test is performed
   * with default init attributes.
   */
  @Nightly
  @Test
  @ThreadLeakLingering(linger = 5000)
  public void testStress() throws InterruptedException, ExecutionException {
    final int numberOfThreads = randomIntBetween(1, 10);
    final int queriesPerThread = scaledRandomIntBetween(5, 25);

    /*
     * This yields a pooling controller effectively, because no cache interfaces are passed.
     */
    @SuppressWarnings("unchecked")
    final Controller controller = getCachingController(initAttributes);

    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
    List<Callable<ProcessingResult>> callables = Lists.newArrayList();
    for (int i = 0; i < numberOfThreads * queriesPerThread; i++) {
      final int dataSetIndex = i;
      callables.add(
          new Callable<ProcessingResult>() {
            public ProcessingResult call() throws Exception {
              Map<String, Object> localAttributes = Maps.newHashMap();
              localAttributes.put(
                  AttributeNames.DOCUMENTS,
                  SampleDocumentData.ALL.get(dataSetIndex % SampleDocumentData.ALL.size()));
              localAttributes.put("dataSetIndex", dataSetIndex);
              return controller.process(localAttributes, getComponentClass());
            }
          });
    }

    try {
      List<Future<ProcessingResult>> results = executorService.invokeAll(callables);
      Multimap<Integer, List<Cluster>> clusterings = ArrayListMultimap.create();

      // Group results by query
      for (Future<ProcessingResult> future : results) {
        final ProcessingResult processingResult = future.get();
        final Integer dataSetIndex = (Integer) processingResult.getAttributes().get("dataSetIndex");
        clusterings.put(dataSetIndex, processingResult.getClusters());
      }

      // Make sure results are the same within each data set
      for (Integer dataSetIndex : clusterings.keySet()) {
        Collection<List<Cluster>> clustering = clusterings.get(dataSetIndex);
        Iterator<List<Cluster>> iterator = clustering.iterator();
        if (!iterator.hasNext()) {
          continue;
        }

        final List<Cluster> firstClusterList = iterator.next();
        Assertions.assertThat(firstClusterList).isNotEmpty();
        while (iterator.hasNext()) {
          assertThatClusters(firstClusterList).isEquivalentTo(iterator.next());
        }
      }
    } finally {
      executorService.shutdown();
    }
  }
  @Override
  public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
      throws InterruptedException {

    List<TrackedCallable<T>> trackedTaskList = executorCore.registerCallableList(tasks);

    return executorCore.trackFutureList(executor.invokeAll(trackedTaskList), trackedTaskList);
  }
 @Override
 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
     throws InterruptedException {
   List<Future<T>> futures = service.invokeAll(tasks);
   for (Future<?> future : futures) {
     pendingTasks.add(future);
   }
   return futures;
 }
示例#22
0
  public void connectChildren(final List<? extends DataItem> children, final DataFolder parent) {

    final ArrayList<AddTypeTagsCallable> callables = new ArrayList<>();
    final ArrayList<DataItemCreatedEvent> events = new ArrayList<>();

    // edit databeans in EDT
    ThreadUtils.runInEDT(
        new Runnable() {
          @Override
          public void run() {
            for (DataItem child : children) {
              // was it already connected?
              boolean wasConnected = child.getParent() != null;
              if (!wasConnected) {
                // prepare event, but don't send it yet
                events.add(new DataItemCreatedEvent(child));
              }

              // connect to this
              child.setParent(parent);

              // add
              parent.children.add(child);

              // prepare type tagging callables
              if (child instanceof DataBean) {
                callables.add(new AddTypeTagsCallable((DataBean) child));
              }
            }
          }
        });

    // run type tagging in parallel in background threads
    try {
      // run callables and wait until all have finished
      List<Future<Object>> futures = executor.invokeAll(callables);

      for (Future<Object> future : futures) {
        // check callable for exception, and throw if found
        future.get();
      }

      // dispatch events in EDT
      ThreadUtils.runInEDT(
          new Runnable() {
            @Override
            public void run() {
              for (DataItemCreatedEvent event : events) {
                dispatchEvent(event);
              }
            }
          });

    } catch (InterruptedException | ExecutionException e) {
      Session.getSession().getApplication().reportExceptionThreadSafely(e);
    }
  }
示例#23
0
 /** invokeAll(null) throws NullPointerException */
 public void testInvokeAll1() throws Throwable {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     try {
       e.invokeAll(null);
       shouldThrow();
     } catch (NullPointerException success) {
     }
   }
 }
示例#24
0
 /** timed invokeAll(null) throws NullPointerException */
 public void testTimedInvokeAll1() throws Throwable {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     try {
       e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
       shouldThrow();
     } catch (NullPointerException success) {
     }
   }
 }
  @Override
  public List<BulkUpdateObjectIdAndChangeToken> bulkUpdateProperties(
      CallContext callContext,
      String repositoryId,
      List<BulkUpdateObjectIdAndChangeToken> objectIdAndChangeTokenList,
      Properties properties,
      List<String> addSecondaryTypeIds,
      List<String> removeSecondaryTypeIds,
      ExtensionsData extension) {
    // //////////////////
    // General Exception
    // //////////////////
    // Each permission is checked at each execution
    exceptionService.invalidArgumentRequiredCollection(
        "objectIdAndChangeToken", objectIdAndChangeTokenList);
    exceptionService.invalidArgumentSecondaryTypeIds(repositoryId, properties);

    // //////////////////
    // Body of the method
    // //////////////////
    List<BulkUpdateObjectIdAndChangeToken> results =
        new ArrayList<BulkUpdateObjectIdAndChangeToken>();

    ExecutorService executor = Executors.newCachedThreadPool();
    List<BulkUpdateTask> tasks = new ArrayList<>();
    for (BulkUpdateObjectIdAndChangeToken objectIdAndChangeToken : objectIdAndChangeTokenList) {
      tasks.add(
          new BulkUpdateTask(
              callContext,
              repositoryId,
              objectIdAndChangeToken,
              properties,
              addSecondaryTypeIds,
              removeSecondaryTypeIds,
              extension));
    }

    try {
      List<Future<BulkUpdateObjectIdAndChangeToken>> _results = executor.invokeAll(tasks);
      for (Future<BulkUpdateObjectIdAndChangeToken> _result : _results) {
        try {
          BulkUpdateObjectIdAndChangeToken result = _result.get();
          results.add(result);
        } catch (Exception e) {
          // TODO log
          // do nothing
        }
      }
    } catch (InterruptedException e1) {
      // TODO log
      e1.printStackTrace();
    }

    return results;
  }
  @Test
  public void checkOnlyOneThreadExecutesPing() throws InterruptedException, ExecutionException {
    Callable<PingResult> task = createTask();
    List<Callable<PingResult>> tasks = Collections.nCopies(3, task);
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    List<Future<PingResult>> futures = executorService.invokeAll(tasks);

    assertEquals("We are fine.", futures.get(0).get().getMessage());
    assertEquals("only for initialization", futures.get(1).get().getMessage());
    assertEquals("only for initialization", futures.get(2).get().getMessage());
  }
示例#27
0
 /** invokeAll(c) returns results of all completed tasks in c */
 public void testInvokeAll5() throws Throwable {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     List<Callable<String>> l = new ArrayList<Callable<String>>();
     l.add(new StringTask());
     l.add(new StringTask());
     List<Future<String>> futures = e.invokeAll(l);
     assertEquals(2, futures.size());
     for (Future<String> future : futures) assertSame(TEST_STRING, future.get());
   }
 }
示例#28
0
 /** timed invokeAll(null time unit) throws NullPointerException */
 public void testTimedInvokeAllNullTimeUnit() throws Throwable {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     List<Callable<String>> l = new ArrayList<Callable<String>>();
     l.add(new StringTask());
     try {
       e.invokeAll(l, MEDIUM_DELAY_MS, null);
       shouldThrow();
     } catch (NullPointerException success) {
     }
   }
 }
 @Test
 public void testInvokeAllTimeoutSuccess() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testInvokeAll");
   assertFalse(executor.isShutdown());
   // Only one task
   ArrayList<Callable<String>> tasks = new ArrayList<Callable<String>>();
   tasks.add(new BasicTestTask());
   List<Future<String>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), 1);
   assertEquals(futures.get(0).get(), BasicTestTask.RESULT);
   // More tasks
   tasks.clear();
   for (int i = 0; i < COUNT; i++) {
     tasks.add(new BasicTestTask());
   }
   futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), COUNT);
   for (int i = 0; i < COUNT; i++) {
     assertEquals(futures.get(i).get(), BasicTestTask.RESULT);
   }
 }
示例#30
0
 /** invokeAll(c) throws NullPointerException if c has null elements */
 public void testInvokeAll3() throws InterruptedException {
   ExecutorService e = new ForkJoinPool(1);
   try (PoolCleaner cleaner = cleaner(e)) {
     List<Callable<String>> l = new ArrayList<Callable<String>>();
     l.add(new StringTask());
     l.add(null);
     try {
       e.invokeAll(l);
       shouldThrow();
     } catch (NullPointerException success) {
     }
   }
 }