@Override
  public void dispose() {
    if (!hasAlreadyShutdown.getAndSet(true) && executorService != null) {

      for (final Future<?> job : jobs) {
        if (!job.isCancelled() && !job.isDone()) {
          job.cancel(true);
        }
      }

      executorService.shutdown(); // Disable new tasks from being submitted
      try {
        // Wait a while for existing tasks to terminate
        if (!executorService.awaitTermination(AWAIT_TERMINATION_TIMEOUT, TimeUnit.SECONDS)) {
          executorService.shutdownNow(); // Cancel currently executing tasks
          // Wait a while for tasks to respond to being cancelled
          if (!executorService.awaitTermination(AWAIT_TERMINATION_TIMEOUT, TimeUnit.SECONDS)) {
            LOG.error("Thread pool did not terminate.");
          }
        }
      } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        executorService.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
      }

      executorService.shutdown();
    }
  }
 /** Stop the RPC service */
 @LogMessageDocs({
   @LogMessageDoc(
       level = "WARN",
       message = "Failed to cleanly shut down RPC server",
       explanation = "Could not close all open sockets cleanly"),
   @LogMessageDoc(
       level = "WARN",
       message = "Interrupted while shutting down RPC server",
       explanation = "Could not close all open sockets cleanly")
 })
 public void shutdown() {
   shutDown = true;
   try {
     if (!cg.close().await(5, TimeUnit.SECONDS)) {
       logger.warn("Failed to cleanly shut down RPC server");
       return;
     }
     if (clientBootstrap != null) clientBootstrap.releaseExternalResources();
     clientBootstrap = null;
     if (serverBootstrap != null) serverBootstrap.releaseExternalResources();
     serverBootstrap = null;
     if (pipelineFactory != null) pipelineFactory.releaseExternalResources();
     pipelineFactory = null;
     if (bossExecutor != null) bossExecutor.shutdown();
     bossExecutor = null;
     if (workerExecutor != null) workerExecutor.shutdown();
     workerExecutor = null;
   } catch (InterruptedException e) {
     logger.warn("Interrupted while shutting down RPC server");
   }
   logger.debug("Internal floodlight RPC shut down");
 }
Ejemplo n.º 3
0
  @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);
    }
  }
Ejemplo n.º 4
0
  public static void main(String[] args) throws Exception {
    Date date = new Date();
    inputString = new ArrayList<String>();
    ans = new ArrayList();
    ans2 = new ArrayList();
    if (args.length == 0) {
      System.err.println("[-iu] [-t THREAD_COUNT] [-o OUTPUT] [FILES...]");
      System.exit(1);
    }

    try {
      readKeys(args);
    } catch (Exception e) {
      System.err.println("Error in set keys :" + e.getMessage());
      System.exit(1);
    }

    queue = new LinkedBlockingQueue();
    service = Executors.newFixedThreadPool(numberThreads);
    Sorter sorter[] = new Sorter[numberThreads];

    try {
      reader(inputString);
    } catch (Exception e) {
      System.err.println("Error in reader");
      System.exit(1);
    }

    for (int i = 0; i < numberThreads; i++) {
      sorter[i] = new Sorter(i);
      sorter[i].start();
    }

    for (int i = 0; i < numberThreads; i++) {
      sorter[i].join();
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    Merge merge = new Merge(ans2, 0);
    merge.run();
    merge.join();

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    try {
      printAnswer(outputFile);
    } catch (Exception e) {
      System.err.println("Error in print answer");
      System.exit(1);
    }
    Date date2 = new Date();
    System.out.println(date2.getTime() - date.getTime());
  }
  @Test
  public void 用途_ワークキュー() throws Exception {
    o.l1("【どういうこと?】").e();
    o.l2("キューイングされたタスクを、順にデキューして、順に別のスレッドで実行。").e();

    o.l1("【どうすれば?】").e();
    o.l2("java.util.concurrent.Executors.newSingleThreadExecutor()ファクトリメソッドを使用。").e();

    o.l1("【たとえば?】").e();
    o.l2("newSingleThreadExecutor()でワークキューを作成。").e();

    o.l3("タスクがRunnableの場合").e();
    NameDecorateRunner runTask1 = new NameDecorateRunner("task1", 2);
    NameDecorateRunner runTask2 = new NameDecorateRunner("task2", 1);

    // executeされたタスクは1つの別スレッドで順々に処理される。
    ExecutorService executor = Executors.newSingleThreadExecutor();

    // 呼び出し順に処理が行われる
    executor.execute(runTask1);
    executor.execute(runTask2);

    // (ゆるやかな)終了指示
    executor.shutdown();

    // エグゼキューターの完了を待つ
    executor.awaitTermination(10 /* timeout */, TimeUnit.SECONDS);

    assertThat(runTask1.name, is("***task1***"));
    assertThat(runTask2.name, is("***task2***"));

    o.l3("タスクがCallableの場合").e();
    NameDecorateCaller callTask1 = new NameDecorateCaller("task1", 2);
    NameDecorateCaller callTask2 = new NameDecorateCaller("task2", 1);

    executor = Executors.newSingleThreadExecutor();

    Future<String> future1 = executor.submit(callTask1);
    Future<String> future2 = executor.submit(callTask2);

    executor.shutdown();

    // 処理の完了を待つ
    String result1 = future1.get();
    String result2 = future2.get();

    assertThat(result1, is("###task1###"));
    assertThat(result2, is("###task2###"));

    {
      /** 【補】invokeAllメソッドとinvokeAnyメソッド */
      // あるタスクの集まりの完了を待つことができるメソッド。
      // invokeAllメソッドは、タスクをすべて実行し、すべての完了を待つ。
      // invokeAnyメソッドは、タスクをすべて実行し、どれか1つでも完了することを待つ。
    }
  }
Ejemplo n.º 6
0
 @Issue("JENKINS-15816")
 @SuppressWarnings({"unchecked", "rawtypes"})
 @Test
 public void timezoneOfID() throws Exception {
   TimeZone origTZ = TimeZone.getDefault();
   try {
     final Run r;
     String id;
     TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
     ExecutorService svc = Executors.newSingleThreadExecutor();
     try {
       r =
           svc.submit(
                   new Callable<Run>() {
                     @Override
                     public Run call() throws Exception {
                       return new Run(new StubJob(), 1234567890) {};
                     }
                   })
               .get();
       TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
       id = r.getId();
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
     TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
     svc = Executors.newSingleThreadExecutor();
     try {
       assertEquals(id, r.getId());
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
   } finally {
     TimeZone.setDefault(origTZ);
   }
 }
Ejemplo n.º 7
0
  public static void main(String[] args) {

    /////////////////////////////////////////////////////////////////////////////
    // FixedThreadPool
    /////////////////////////////////////////////////////////////////////////////
    {
      // 常に10スレッドをプールするExecutorServiceを生成
      ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

      // タスクを実行
      fixedThreadPool.execute(new TestThread());
      fixedThreadPool.execute(new TestThread());

      // すべてのタスクが終了したらExecutorServiceをシャットダウン
      fixedThreadPool.shutdown();
    }

    /////////////////////////////////////////////////////////////////////////////
    // CachedThreadPool
    /////////////////////////////////////////////////////////////////////////////
    {
      // 必要に応じてスレッドのプール数が変化するExecutorServiceを生成
      ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

      // タスクを実行
      cachedThreadPool.execute(new TestThread());
      cachedThreadPool.execute(new TestThread());

      // すべてのタスクが終了したらExecutorServiceをシャットダウン
      cachedThreadPool.shutdown();
    }

    /////////////////////////////////////////////////////////////////////////////
    // ScheduledThreadPool
    /////////////////////////////////////////////////////////////////////////////
    {
      // 実行間隔を指定してタスクを実行可能なScheduledExecutorServiceを生成
      // (プールするスレッドの最小数は5に指定)
      ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

      // タスクを実行
      scheduledThreadPool.schedule(
          new Runnable() {
            @Override
            public void run() {
              System.out.println("Executed");
            }
          },
          3,
          TimeUnit.SECONDS);

      // すべてのタスクが終了したらScheduledExecutorServiceをシャットダウン
      scheduledThreadPool.shutdown();
    }
  }
Ejemplo n.º 8
0
  public boolean shutdown(int timeout) {

    requestExecutor.shutdown();
    timeoutExecutor.shutdown();
    try {
      return requestExecutor.awaitTermination(timeout, TimeUnit.SECONDS)
          && timeoutExecutor.awaitTermination(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      return false;
    }
  }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
0
  @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();
    }
  }
Ejemplo n.º 11
0
 @Override
 @After
 public void tearDown() throws Exception {
   destroy(buffer);
   if (controller != null) {
     try {
       controller.close();
     } catch (Exception e) {
       // ignored
     }
   }
   executor.shutdown();
   pollerExecutor.shutdown();
   super.tearDown();
 }
  @Override
  public CompletableFuture<Void> destroy() {
    destroyed = true;

    executor.shutdown();
    backgroundExecutor.shutdown();
    communicationExecutor.shutdown();

    listeners.clear();

    clusterCommunicator.removeSubscriber(updateMessageSubject);
    clusterCommunicator.removeSubscriber(updateRequestSubject);
    clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject);
    return CompletableFuture.completedFuture(null);
  }
Ejemplo n.º 13
0
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      System.out.println("java DownloadWeb <output dir>");
      return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    ExecutorService exec = Executors.newCachedThreadPool();

    final String dir = args[0];
    String url = null;

    while ((url = reader.readLine()) != null) {

      final URI uri = URI.create(url);
      String fileName = new File(uri.getPath()).getName();
      final Path filePath = Paths.get(dir, fileName);

      exec.submit(
          new Runnable() {
            @Override
            public void run() {
              try (InputStream in = uri.toURL().openStream()) {
                Files.copy(in, filePath, StandardCopyOption.REPLACE_EXISTING);
                System.out.printf("completed: %s => %s\n", uri, filePath);
              } catch (Exception ex) {
                System.out.printf("failed: %s\n", uri);
              }
            }
          });
    }

    exec.shutdown();
  }
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newFixedThreadPool(5);
    CompletableFuture<String> task1 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": firstTask");
                TimeUnit.SECONDS.sleep(2);
              } catch (Exception e) {
              }
              return "1";
            });
    CompletableFuture<String> task2 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": secondTask");
                TimeUnit.SECONDS.sleep(3);
              } catch (Exception e) {
              }
              return "2";
            });
    // a new thread from the supplied executor will execute third task
    task1.acceptEitherAsync(
        task2,
        (x) -> {
          System.out.println(Thread.currentThread().getName() + ": thirdTask " + x);
        },
        executor);

    TimeUnit.SECONDS.sleep(5);
    System.out.println(Thread.currentThread().getName() + ": " + task1.get());
    executor.shutdown();
  }
Ejemplo n.º 15
0
  private void multicastJoin(int count, final boolean sleep) throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(count);

    final Config config = new Config();
    config.setProperty("hazelcast.wait.seconds.before.join", "5");
    config.getNetworkConfig().getJoin().getMulticastConfig().setMulticastTimeoutSeconds(25);
    final ConcurrentMap<Integer, HazelcastInstance> map =
        new ConcurrentHashMap<Integer, HazelcastInstance>();
    final CountDownLatch latch = new CountDownLatch(count);
    final ExecutorService ex = Executors.newCachedThreadPool();
    for (int i = 0; i < count; i++) {
      final int index = i;
      ex.execute(
          new Runnable() {
            public void run() {
              if (sleep) {
                try {
                  Thread.sleep((int) (1000 * Math.random()));
                } catch (InterruptedException ignored) {
                }
              }
              HazelcastInstance h = nodeFactory.newHazelcastInstance(config);
              map.put(index, h);
              latch.countDown();
            }
          });
    }
    assertOpenEventually(latch);
    for (HazelcastInstance h : map.values()) {
      assertEquals(count, h.getCluster().getMembers().size());
    }
    ex.shutdown();
  }
Ejemplo n.º 16
0
      public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < 4; i++) {
          if (e.getSource() == Answer[i]) {
            // Answer[i].setSelected(false);
            Charge(i);
          }
        }
        if (e.getSource() == Sure) {
          ChargeSpell();
        } else if (e.getSource() == Speak) {
          ExecutorService executorService = Executors.newFixedThreadPool(1);
          executorService.execute(
              new Runnable() {
                public void run() {
                  try {
                    Speak.setEnabled(false);
                    WordTextFile.setText(sound.startRec());
                    Speak.setEnabled(true);
                    System.out.println("done");
                  } catch (Exception e2) {

                  }
                }
              });
          //					Dictionary.takeWordSearch.startSearch();
          executorService.shutdown();
        }
      }
Ejemplo n.º 17
0
 /** 改变标志位停止线程 */
 public void stop_() {
   synchronized (this) {
     isContinue = false;
     watchDataThreadPool.shutdown();
     submitDataThreadPool.shutdown();
   }
 }
Ejemplo n.º 18
0
 public static void main(String args[]) {
   Semaphore s = new Semaphore(5);
   NumberServer n = new NumberServer();
   ExecutorService executorService = Executors.newFixedThreadPool(10);
   List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
   for (int i = 0; i < 10; i++) {
     try {
       s.acquire();
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     executorService.execute(
         new Runnable() {
           public void run() {
             list.add(n.getNumber());
             s.release();
           }
         });
   }
   executorService.shutdown();
   try {
     s.acquire(5);
   } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   for (int i = 0; i < 10; i++) {
     System.out.println(list.get(i));
   }
 }
  public void engage() {
    System.out.println("Starting the Disruptor");
    // starts the event processors
    final RingBuffer<DemoEvent> ringBuf = disruptor.start();

    // now we start the publishers
    List<Future<?>> futures = new ArrayList<Future<?>>();
    ExecutorService execService = Executors.newFixedThreadPool(NUM_PUBLISHERS);

    try {
      for (DisruptorDemoPublisher pub : pubs) {
        futures.add(execService.submit(pub));
      }

      // wait for each publisher to finish
      for (Future<?> f : futures) {
        f.get();
      }

      // this should wait until all events are processed
      disruptor.shutdown();

    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();

    } finally {
      execService.shutdown();
    }
  }
  public String GetKnnAsString(String featureVector) {
    // System.err.println(featureVector);
    // System.err.println(trainingVectors.size());
    FeatureVector fv = new FeatureVector(featureVector, 32);
    PriorityBlockingQueue<CategoryDistances> pbq = new PriorityBlockingQueue<>();
    ExecutorService pool = Executors.newFixedThreadPool(NumWorkers);
    String outp = "";

    for (FeatureVector elem : trainingVectors) {
      pool.execute(new EuclideanWorker(elem, fv, pbq));
    }
    pool.shutdown();
    while (!pool.isTerminated()) {;
    }

    for (int i = 0; i < K; i++) {
      CategoryDistances cd = pbq.poll();
      if (cd == null) {
        break;
      }
      outp += cd.toString() + VectorDelim;
    }
    // System.out.println(outp);
    return outp.substring(0, outp.length() - 1);
  }
Ejemplo n.º 21
0
 public void unInit() {
   if (mExecutorService != null) {
     mExecutorService.shutdown();
     mExecutorService.shutdownNow();
     mExecutorService = null;
   }
 }
Ejemplo n.º 22
0
  public void close() {
    if (shuttingDown.getAndSet(true)) {
      return;
    }

    mutex.lock();
    try {
      while (backgroundCompaction != null) {
        backgroundCondition.awaitUninterruptibly();
      }
    } finally {
      mutex.unlock();
    }

    compactionExecutor.shutdown();
    try {
      compactionExecutor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
    try {
      versions.destroy();
    } catch (IOException ignored) {
    }
    try {
      log.close();
    } catch (IOException ignored) {
    }
    tableCache.close();
    dbLock.release();
  }
Ejemplo n.º 23
0
  // The method executing the task
  @Override
  public void execute() throws BuildException {

    this.log("Starting PlantUML");

    try {
      if (dir != null) {
        final File error = processingSingleDirectory(new File(dir));
        eventuallyFailfast(error);
      }
      for (FileSet fileSet : filesets) {
        final File error = manageFileSet(fileSet);
        eventuallyFailfast(error);
      }
      for (FileList fileList : filelists) {
        final File error = manageFileList(fileList);
        eventuallyFailfast(error);
      }
      if (executorService != null) {
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
      }
      this.log("Nb images generated: " + nbFiles.get());
    } catch (IOException e) {
      e.printStackTrace();
      throw new BuildException(e.toString());
    } catch (InterruptedException e) {
      e.printStackTrace();
      throw new BuildException(e.toString());
    }
  }
  private void callParserThread(
      String[] sources,
      String[] encodings,
      String[] classPaths,
      ArrayList<String> acceptedFiles,
      ArrayList<String> sharedRevisionEntryList,
      Multimap<String, String> invokers)
      throws IOException {
    try {
      int numOfThreads = Runtime.getRuntime().availableProcessors();

      BlockingQueue<String> toProcess =
          new ArrayBlockingQueue<String>(acceptedFiles.size(), false, acceptedFiles);
      ExecutorService executorService = Executors.newFixedThreadPool(numOfThreads);

      for (int i = 0; i < numOfThreads; ++i) {
        ParserRunnable runnerParser =
            new ParserRunnable(
                sources,
                encodings,
                classPaths,
                toProcess,
                sharedRevisionEntryList,
                invokers,
                numOfThreads);
        executorService.submit(runnerParser);
      }

      executorService.shutdown();
      executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 25
0
  @Override
  public synchronized void close() throws SQLException {
    try {
      closeLock.writeLock().lock();
      if (closed) {
        return;
      }
      closed = true;
    } finally {
      closeLock.writeLock().unlock();
    }

    try {
      Collection<ConnectionQueryServices> connectionQueryServices =
          connectionQueryServicesMap.values();
      try {
        SQLCloseables.closeAll(connectionQueryServices);
      } finally {
        connectionQueryServices.clear();
      }
    } finally {
      if (services != null) {
        try {
          services.close();
        } finally {
          ExecutorService executor = services.getExecutor();
          // Even if something wrong happened while closing services above, we still
          // want to set it to null. Otherwise, we will end up having a possibly non-working
          // services instance.
          services = null;
          executor.shutdown();
        }
      }
    }
  }
 @Override
 public void doTraverse(Poset gPoset) {
   DefaultPoset poset = (DefaultPoset) gPoset;
   @SuppressWarnings("unchecked")
   final Queue<VectorClock> ques[] = new Queue[2];
   for (int i = 0; i < 2; ++i) ques[i] = new ConcurrentLinkedQueue<VectorClock>();
   ques[0].add(new VectorClock(poset.width(), 0));
   final AtomicInteger curQue = new AtomicInteger(0);
   final CyclicBarrier barrier = new CyclicBarrier(poolSize, new Tripper(ques, curQue));
   final ExecutorService pool = Executors.newFixedThreadPool(poolSize);
   for (int i = 0; i < poolSize; ++i) {
     pool.submit(new Worker(poset, ques, curQue, barrier, enumerator.fork()));
   }
   pool.shutdown();
   try {
     if (!pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)) {
       pool.shutdownNow();
       if (!pool.awaitTermination(1, TimeUnit.SECONDS))
         logger.error("Thread pool did not terminate.");
     }
   } catch (InterruptedException e) {
     pool.shutdownNow();
     logger.warn("Thread pool is forced to shutdown.");
   }
 }
Ejemplo n.º 27
0
 public final void a() {
   try {
     cm.a()
         .b()
         .a(
             "Crashlytics",
             (new StringBuilder("Executing shutdown hook for ")).append(a).toString());
     b.shutdown();
     if (!b.awaitTermination(c, d)) {
       cm.a()
           .b()
           .a(
               "Crashlytics",
               (new StringBuilder())
                   .append(a)
                   .append(
                       " did not shut down in the allocated time. Requesting immediate shutdown.")
                   .toString());
       b.shutdownNow();
     }
     return;
   } catch (InterruptedException interruptedexception) {
     cm.a()
         .b()
         .a(
             "Crashlytics",
             String.format(
                 Locale.US,
                 "Interrupted while waiting for %s to shut down. Requesting immediate shutdown.",
                 new Object[] {a}));
   }
   b.shutdownNow();
 }
Ejemplo n.º 28
0
  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
    */
  }
Ejemplo n.º 29
0
  @Override
  public String test(FailureDetector failureDetector) throws Exception {
    Node node = Iterables.get(failureDetectorConfig.getCluster().getNodes(), 0);
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Listener listener = new Listener(failureDetectorConfig.getTime());
    failureDetector.addFailureDetectorListener(listener);

    ExecutorService threadPool = Executors.newFixedThreadPool(11);

    for (int i = 0; i < 10; i++)
      threadPool.submit(
          new NodeAccessorRunnable(failureDetector, node, countDownLatch, null, null, null, 0, 10));

    threadPool.submit(new TimedUnavailability(failureDetector, node, countDownLatch));

    threadPool.shutdown();

    // If we get stuck, we should give the user the opportunity to get a
    // thread dump.
    if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
      System.out.println("Threads appear to be stuck");
      threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    }

    return Class.forName(failureDetectorConfig.getImplementationClassName()).getSimpleName()
        + ", "
        + listener.getDelta();
  }
  public void start() throws ExecutionException, InterruptedException {

    // Use the default MtGox settings
    Exchange mtGoxExchange = ExchangeFactory.INSTANCE.createExchange(MtGoxExchange.class.getName());

    // Configure BTC/USD ticker stream for MtGox
    ExchangeStreamingConfiguration btcusdConfiguration =
        new MtGoxStreamingConfiguration(10, 10000, Currencies.BTC, Currencies.USD, false);

    // Interested in the public streaming market data feed (no authentication)
    StreamingExchangeService btcusdStreamingMarketDataService =
        mtGoxExchange.getStreamingExchangeService(btcusdConfiguration);

    // Requesting initial order book using the polling service
    PollingMarketDataService marketDataService = mtGoxExchange.getPollingMarketDataService();
    MarketDataRunnable.book = marketDataService.getPartialOrderBook(Currencies.BTC, Currencies.USD);

    // Open the connections to the exchange
    btcusdStreamingMarketDataService.connect();

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<?> mtGoxMarketDataFuture =
        executorService.submit(new MarketDataRunnable(btcusdStreamingMarketDataService));

    // the thread waits here until the Runnable is done.
    mtGoxMarketDataFuture.get();

    executorService.shutdown();

    // Disconnect and exit
    System.out.println(Thread.currentThread().getName() + ": Disconnecting...");
    btcusdStreamingMarketDataService.disconnect();
  }