@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);
    }
  }
Beispiel #2
0
 @Override
 public void unregistered(SelectionKey key) {
   serverHelperExecutor.shutdown();
   storageHelperExecutor.shutdown();
   try {
     serverHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ex) {
     logger.debug("Executor Termination", ex);
   }
   logger.info("Server stopped listening at {}", address);
 }
  @Override
  public void dispose() {
    myDisposed = true;
    cancelAllRequests();

    if (myThreadToUse == ThreadToUse.POOLED_THREAD) {
      myExecutorService.shutdown();
    } else if (myThreadToUse == ThreadToUse.OWN_THREAD) {
      myExecutorService.shutdown();
      ((ThreadPoolExecutor) myExecutorService).getQueue().clear();
    }
  }
Beispiel #4
0
  public static <T> List<T> executeAndGetResult(
      Collection<? extends Callable<T>> tasks, long waitingTimeInMillis) {
    ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
    List<T> finalResults = new ArrayList<T>(tasks.size());
    List<Future<T>> temporaryResults = new ArrayList<Future<T>>(tasks.size());

    try {
      for (Callable<T> task : tasks) {
        Future<T> future = executor.submit(task);
        temporaryResults.add(future);
      }
      executor.awaitTermination(waitingTimeInMillis, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } finally {
      executor.shutdown();
    }

    finalResults = new ArrayList<T>(temporaryResults.size());

    for (Future<T> result : temporaryResults) {
      try {
        finalResults.add(result.get());
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      } catch (ExecutionException e) {
        throw new RuntimeException(e);
      }
    }

    return finalResults;
  }
  public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();
    CompletionService<String> service = new ExecutorCompletionService<String>(executor);

    ReportRequest faceRequest = new ReportRequest("Face", service);
    ReportRequest onlineRequest = new ReportRequest("Online", service);
    Thread faceThread = new Thread(faceRequest);
    Thread onlineThread = new Thread(onlineRequest);

    ReportProcessor processor = new ReportProcessor(service);
    Thread processThread = new Thread(processor);

    System.out.println("Main: Starting the Threads");
    faceThread.start();
    onlineThread.start();
    processThread.start();

    try {
      System.out.println("Main: Waiting for the report generators.");
      faceThread.join();
      onlineThread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("Main: Shutting down the executor.");
    executor.shutdown();
    try {
      executor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    processor.setEnd(true);
    System.out.println("Main: Ends");
  }
Beispiel #6
0
  public static void main(String[] args) throws Exception {
    parseArguments(args);

    List<Iterator<String>> segments = Splitter.split(inputFilePath, numberOfThreads);

    List<Future<Analytic>> futures = new ArrayList<Future<Analytic>>(segments.size());
    ExecutorService threadPool = Executors.newFixedThreadPool(segments.size());
    for (final Iterator<String> segment : segments) {
      Future<Analytic> future =
          threadPool.submit(
              new Callable<Analytic>() {
                @Override
                public Analytic call() throws Exception {
                  return new Analyzer(segment).parse();
                }
              });
      futures.add(future);
    }

    try {
      ArrayList<Analytic> analytics = new ArrayList<Analytic>(futures.size());
      for (Future<Analytic> future : futures) {
        analytics.add(future.get());
      }
      Analytic result = Synthesizer.synthesize(analytics);
      writeResult(result);
    } finally {
      threadPool.shutdown();
    }
  }
  // Concurrent insertion & then iterator test.
  public static void testNonBlockingIdentityHashMapIterator() throws InterruptedException {
    final int ITEM_COUNT1 = 1000;
    final int THREAD_COUNT = 5;
    final int PER_CNT = ITEM_COUNT1 / THREAD_COUNT;
    final int ITEM_COUNT = PER_CNT * THREAD_COUNT; // fix roundoff for odd thread counts

    NonBlockingIdentityHashMap<Long, TestKey> nbhml =
        new NonBlockingIdentityHashMap<Long, TestKey>();
    // use a barrier to open the gate for all threads at once to avoid rolling
    // start and no actual concurrency
    final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT);
    final ExecutorService ex = Executors.newFixedThreadPool(THREAD_COUNT);
    final CompletionService<Object> co = new ExecutorCompletionService<Object>(ex);
    for (int i = 0; i < THREAD_COUNT; i++) {
      co.submit(new NBHMLFeeder(nbhml, PER_CNT, barrier, i * PER_CNT));
    }
    for (int retCount = 0; retCount < THREAD_COUNT; retCount++) {
      co.take();
    }
    ex.shutdown();

    assertEquals("values().size()", ITEM_COUNT, nbhml.values().size());
    assertEquals("entrySet().size()", ITEM_COUNT, nbhml.entrySet().size());
    int itemCount = 0;
    for (TestKey K : nbhml.values()) itemCount++;
    assertEquals("values().iterator() count", ITEM_COUNT, itemCount);
  }
  @Override
  public Boolean call() throws Exception {

    long timeoutMillis = 5000;

    try {
      getServersFile();
      getZkRunning();

      while (true) {
        while (!restartQueue.isEmpty()) {
          LOG.debug("Restart queue size [" + restartQueue.size() + "]");
          RestartHandler handler = restartQueue.poll();
          Future<ScriptContext> runner = pool.submit(handler);
          ScriptContext scriptContext = runner.get(); // blocking call
          if (scriptContext.getExitCode() != 0) restartQueue.add(handler);
        }

        try {
          Thread.sleep(timeoutMillis);
        } catch (InterruptedException e) {
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      LOG.error(e);
      pool.shutdown();
      throw e;
    }
  }
    public NonBlockingIdentityHashMap<Long, TestKey> getMapMultithreaded()
        throws InterruptedException, ExecutionException {
      final int threadCount = _items.keySet().size();
      final NonBlockingIdentityHashMap<Long, TestKey> map =
          new NonBlockingIdentityHashMap<Long, TestKey>();

      // use a barrier to open the gate for all threads at once to avoid rolling start and no actual
      // concurrency
      final CyclicBarrier barrier = new CyclicBarrier(threadCount);
      final ExecutorService ex = Executors.newFixedThreadPool(threadCount);
      final CompletionService<Integer> co = new ExecutorCompletionService<Integer>(ex);
      for (Integer type : _items.keySet()) {
        // A linked-list of things to insert
        List<TestKey> items = _items.get(type);
        TestKeyFeederThread feeder = new TestKeyFeederThread(type, items, map, barrier);
        co.submit(feeder);
      }

      // wait for all threads to return
      int itemCount = 0;
      for (int retCount = 0; retCount < threadCount; retCount++) {
        final Future<Integer> result = co.take();
        itemCount += result.get();
      }
      ex.shutdown();
      return map;
    }
Beispiel #10
0
 @AfterClass
 public static void tearDown() throws InterruptedException, ExecutionException, IOException {
   DirDataImpl dirData = new DirDataImpl();
   DirDataImpl.setNumber(3334);
   List<String> paths = dirData.dividePath(rootPath, 30, THREADS);
   List<Future<String>> list = new ArrayList<>();
   try {
     for (String p : paths) {
       Future<String> submit =
           executor.submit(
               () -> {
                 dirData.delDir(p, 6);
                 return "It done!";
               });
       list.add(submit);
     }
     for (Future<String> future : list) {
       future.get();
     }
   } finally {
     executor.shutdown();
     while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
       LOG.info("Awaiting completion of threads.");
     }
   }
   FileUtils.deleteDirectory(new File(rootPath));
 }
  public static void main(String[] args) throws InterruptedException, ExecutionException {

    List<Future<String>> futures = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 1000; i <= 1010; i++) {
      futures.add(executor.submit(getTask(i)));
    }

    futures.add(executor.submit(getTask(10000000)));

    for (Future<String> future : futures) {
      System.out.println(future.get());
    }

    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);

    /* output
    500500
    501501
    502503
    503506
    504510
    505515
    506521
    507528
    508536
    509545
    510555
    50000005000000
    */
  }
  private int[] computeClusterNumberRange(int min, int max, int hop, Optimizer optimizer)
      throws ExecutionException, InterruptedException {
    ExecutorService executor;
    if (parallelWorkers > 1) {
      executor = Executors.newFixedThreadPool(2);
    } else {
      executor = Executors.newFixedThreadPool(1);
    }
    ConcurrentMap<Integer, Double> sharedScores = new ConcurrentHashMap<>();
    SearchSpaceBoundaryFinder_old upperBoundFinder =
        new SearchSpaceUpperBoundaryFinder_old(min, max, hop, optimizer, sharedScores);
    Future<Integer> futureUpperBound = executor.submit(upperBoundFinder);
    SearchSpaceBoundaryFinder_old lowerBoundFinder =
        new SearchSpaceLowerBoundaryFinder_old(min, max, hop, optimizer, sharedScores);
    Future<Integer> futureLowerBound = executor.submit(lowerBoundFinder);
    executor.shutdown();
    int[] r = new int[2];
    Integer realMin = futureLowerBound.get();
    Integer realMax = futureUpperBound.get();
    r[0] = realMin == null ? -1 : realMin;
    r[1] = realMax == null ? -1 : realMax;

    scores.putAll(lowerBoundFinder.getSplitsAndScores());
    // scores.putAll(upperBoundFinder.getSplitsAndScores());
    return r;
  }
  @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");
  }
 public static void test(IntGenerator go, int count) {
   System.out.println("Press Control-C to exit");
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < count; i++) {
     exec.execute(new EventChecker(go, i));
   }
   exec.shutdown();
 }
 /** Demonstrating the failing of the pre/post conditions of Even. */
 public static void main(String[] args) {
   ExecutorService e = Executors.newFixedThreadPool(10);
   Even ev = new Even();
   for (int i = 0; i < 10; i++) {
     e.execute(new EvenTask(ev));
   }
   e.shutdown();
 }
 public <T> Collection<T> getParallelResults(List<Node<T>> nodes) throws InterruptedException {
   ExecutorService exec = Executors.newCachedThreadPool();
   Queue<T> resultQueue = new ConcurrentLinkedQueue<T>();
   parallelRecursive(exec, nodes, resultQueue);
   exec.shutdown();
   exec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
   return resultQueue;
 }
  /**
   * Testing threads thoroughly seems to be a lot of fun, I am not sure yet how to properly do that.
   * This test tests priority order and total sum received is equal to total sum sent. It also
   * simulates clients random hanging.
   */
  @Test
  public void testReceiveData() {

    DecorateCheckOrderAndCountSumMarshaller sumAppender =
        new DecorateCheckOrderAndCountSumMarshaller();
    QueueWorker worker = new QueueWorker(sumAppender);
    Thread workerThread = new Thread(worker);

    // run 20 clients, 10.000 items will be generated per client as defined in
    // src/test/properties/app.properties
    for (int i = 0; i < 20; i++) {
      Runnable clientHangSimulator = null;
      if (i % 5 == 0) {
        // simulate occasional client hang for four of the total twenty clients and check worker is
        // not biased.
        clientHangSimulator =
            () -> {
              if (ThreadLocalRandom.current().nextInt(1001) % 1000 == 0) {
                try {
                  Thread.sleep(500L);
                } catch (InterruptedException e) {
                  Thread.currentThread().interrupt();
                }
              }
            };
      }
      executorService.execute(new DataGeneratorTask(clientHangSimulator));
    }

    workerThread.start();

    try {
      barrier.await();
      System.out.println("Fired test");
      Thread.sleep(1000);
      executorService.shutdown();
      // runs actually much faster, may need update if item count per client is drastically
      // increased in app.properties
      executorService.awaitTermination(2 * 60, TimeUnit.SECONDS);
      System.out.println("exe service awaited");
    } catch (InterruptedException | BrokenBarrierException e) {
      e.printStackTrace();
    }

    try {
      workerThread.join(Long.MAX_VALUE);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Assert.assertEquals(
        "Sum generated does not match sum received",
        sumAppender.getSum(),
        AppContext.getInstance().getTotalGeneratedAmount());
    Assert.assertFalse("Worker didn't exit successfully", workerThread.isAlive());
  }
  @Test
  public void testPostregisteredExecutionCallbackCompletableFuture() throws Exception {
    HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance();
    Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original");
    originalField.setAccessible(true);
    HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy);
    NodeEngine nodeEngine = hz.node.nodeEngine;
    ExecutionService es = nodeEngine.getExecutionService();

    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
      Future future =
          executorService.submit(
              new Callable<String>() {
                @Override
                public String call() {
                  try {
                    return "success";
                  } finally {
                    latch1.countDown();
                  }
                }
              });

      final ICompletableFuture completableFuture = es.asCompletableFuture(future);
      latch1.await(30, TimeUnit.SECONDS);

      final AtomicReference reference = new AtomicReference();
      completableFuture.andThen(
          new ExecutionCallback() {
            @Override
            public void onResponse(Object response) {
              reference.set(response);
              latch2.countDown();
            }

            @Override
            public void onFailure(Throwable t) {
              reference.set(t);
              latch2.countDown();
            }
          });

      latch2.await(30, TimeUnit.SECONDS);
      if (reference.get() instanceof Throwable) {
        ((Throwable) reference.get()).printStackTrace();
      }

      assertEquals("success", reference.get());

    } finally {
      executorService.shutdown();
    }
  }
  public static void main(String[] args) {
    // Create a thread pool with two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);

    System.out.println("Thread 1\t\tThread 2\t\tBalance");

    executor.execute(new DepositTask());
    executor.execute(new WithDrawTask());
    executor.shutdown();
  }
 /** Wait out termination of a thread pool or fail doing so */
 public void joinPool(ExecutorService exec) {
   try {
     exec.shutdown();
     assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
   } catch (SecurityException ok) {
     // Allowed in case test doesn't have privs
   } catch (InterruptedException ie) {
     fail("Unexpected exception");
   }
 }
  @Test
  @Ignore
  public void testCHMAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      System.out.println("Testing " + runs + " million entries");
      final long entries = runs * 1000 * 1000L;
      final ConcurrentMap<String, AtomicInteger> map =
          new ConcurrentHashMap<String, AtomicInteger>((int) (entries * 5 / 4), 1.0f, 1024);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    String key = sb.toString();
                    AtomicInteger count = map.get(key);
                    if (count == null) {
                      map.put(key, new AtomicInteger());
                      count = map.get(key);
                    }
                    count.getAndIncrement();
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(10, TimeUnit.MINUTES);
        printStatus();
        long time = System.currentTimeMillis() - start;
        System.out.printf("Throughput %.1f M ops/sec%n", threads * entries / 1000.0 / time);
      }
    }
  }
Beispiel #22
0
 private void shutdownExecutor(ExecutorService executor) {
   if (executor == null) {
     return;
   }
   executor.shutdown();
   try {
     executor.awaitTermination(10, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   }
 }
  public void serve() {
    try {
      serverTransport_.listen();
    } catch (TTransportException ttx) {
      LOGGER.error("Error occurred during listening.", ttx);
      return;
    }

    stopped_ = false;
    while (!stopped_) {
      int failureCount = 0;
      try {
        TTransport client = serverTransport_.accept();
        WorkerProcess wp = new WorkerProcess(client);
        try {
          executorService_.execute(wp);
        } catch (RejectedExecutionException ree) {
          ++failureCount;
          LOGGER.warn("Execution rejected.", ree);
          client.close();
        }
      } catch (TTransportException ttx) {
        if (!stopped_) {
          ++failureCount;
          LOGGER.warn("Transport error occurred during acceptance of message.", ttx);
        }
      } catch (Error e) {
        if (!stopped_) {
          ++failureCount;
          LOGGER.warn("Uncaught error.", e);
        }
      }
    }

    executorService_.shutdown();

    // Loop until awaitTermination finally does return without a interrupted
    // exception. If we don't do this, then we'll shut down prematurely. We want
    // to let the executorService clear it's task queue, closing client sockets
    // appropriately.
    long timeoutMS = options_.stopTimeoutUnit.toMillis(options_.stopTimeoutVal);
    long now = System.currentTimeMillis();
    while (timeoutMS >= 0) {
      try {
        executorService_.awaitTermination(timeoutMS, TimeUnit.MILLISECONDS);
        break;
      } catch (InterruptedException ix) {
        long newnow = System.currentTimeMillis();
        timeoutMS -= (newnow - now);
        now = newnow;
      }
    }
  }
  @Test
  @Ignore
  public void testAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    //        int runs = Integer.getInteger("runs", 10);
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      final long entries = runs * 1000 * 1000L;
      final SharedHashMap<CharSequence, LongValue> map = getSharedMap(entries * 4 / 3, 1024, 24);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  LongValue value = nativeLongValue();
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    map.acquireUsing(sb, value);
                    long n = value.addAtomicValue(1);
                    assert n >= 0 && n < 1000 : "Counter corrupted " + n;
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(runs / 10 + 1, TimeUnit.MINUTES);
        long time = System.currentTimeMillis() - start;
        System.out.printf(
            "Throughput %.1f M ops/sec%n", threads * entries / independence / 1000.0 / time);
      }
      printStatus();
      map.close();
    }
  }
Beispiel #25
0
 private synchronized void shutdown() {
   if (!exe.isShutdown()) {
     freeCUObjectsMemory();
   }
   exe.shutdown();
   try {
     System.err.println(
         "cuda device " + Id + " freed ? " + exe.awaitTermination(10, TimeUnit.SECONDS));
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Beispiel #26
0
 public static void main(String[] args) {
   ExecutorService exec = Executors.newCachedThreadPool();
   AtomicityTest at = new AtomicityTest();
   exec.execute(at);
   while (true) {
     int val = at.getValue();
     if (val % 2 != 0) {
       at.cancelTask();
       System.out.println(val);
       break;
     }
   }
   exec.shutdown();
 }
Beispiel #27
0
 public static boolean init() {
   synchronized (cudaEngines) {
     System.err.println("---------Initializing Cuda----------------");
     try {
       extractAndLoadNativeLibs();
       JCudaDriver.setExceptionsEnabled(true);
       JCudaDriver.cuInit(0);
       compileKernelsPtx();
       // Obtain the number of devices
       int deviceCountArray[] = {0};
       JCudaDriver.cuDeviceGetCount(deviceCountArray);
       availableDevicesNb = deviceCountArray[0];
       if (availableDevicesNb == 0) return false;
       availableDevicesNb = NB_OF_DEVICE_TO_USE; // TODO
       initialization = Executors.newCachedThreadPool();
       System.out.println("Found " + availableDevicesNb + " GPU devices");
       for (int i = 0 /*-NB_OF_DEVICE_TO_USE*/; i < availableDevicesNb; i++) {
         final int index = i;
         Future<?> initJob =
             initialization.submit(
                 new Runnable() {
                   public void run() {
                     System.err.println("Initializing device n°" + index);
                     cudaEngines.put(index, new CudaEngine(index));
                   }
                 });
         initJob.get();
         initialization.shutdown();
       }
     } catch (InterruptedException
         | ExecutionException
         | IOException
         | CudaException
         | UnsatisfiedLinkError e) {
       e.printStackTrace();
       System.err.println("---------Cannot initialize Cuda !!! ----------------");
       return false;
     }
     Runtime.getRuntime()
         .addShutdownHook(
             new Thread() {
               @Override
               public void run() {
                 CudaEngine.stop();
               }
             });
     System.out.println("---------Cuda Initialized----------------");
     return true;
   }
 }
  @Override
  public View getInfoContents(Marker marker) {

    executor = Executors.newFixedThreadPool(NTHREDS);

    LayoutInflater inflater =
        (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = inflater.inflate(R.layout.cluster_item_info_window, null);

    holder = new ShowInfoWindowViewHolder(view);

    view.setTag(holder);

    holder.address.setText(String.valueOf(mPropertyObject.getAddress()));

    //        holder.latitude.setText(String.valueOf(mPropertyObject.getGeopoint().getLatitude()));
    //
    // holder.longitude.setText(String.valueOf(mPropertyObject.getGeopoint().getLongitude()));

    if (executor != null) {

      Future<Bitmap> streetViewFuture =
          executor.submit(new FetchStreetView<Bitmap>(mPropertyObject.getPhoto().getUrl()));

      // This will make the executor accept no new threads
      // and finish all existing threads in the queue
      executor.shutdown();

      // Wait until all threads are finish
      while (!executor.isTerminated()) {}

      try {

        if (streetViewFuture.get() != null) {
          holder.streetView.setImageBitmap(streetViewFuture.get());
          Log.i(TAG, streetViewFuture.get().toString());
        }
      } catch (InterruptedException e) {

        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    }

    // Returning the view containing InfoWindow contents
    return view;
  }
  public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();

    // Create and launch 100 threads
    for (int i = 0; i < 100; i++) {
      executor.execute(new AddPennyTask());
    }

    executor.shutdown();

    // Wait until all tasks are finished
    while (!executor.isTerminated()) {}

    System.out.println("What is balance? " + account.getCount());
  }
Beispiel #30
0
 @Override
 public Board solve(Board in) {
   if (useBacktracking) {
     return solve_mdfs(in);
   } else {
     if (nThreads == 1) {
       return solve_ldfs(in);
     } else {
       ExecutorService pool = Executors.newFixedThreadPool(nThreads);
       Board ret = solve_pndfs(in, pool);
       pool.shutdown();
       return ret;
     }
   }
 }