并行迭代for循环中的所有机器并检查它们是上升还是下降?

时间:2018-05-29 19:06:42

标签: java multithreading concurrency thread-safety executorservice

我有ArrayList中的计算机列表。我正在检查所有这些机器是否已经启动,所以我正在对它们进行http调用,如果它们响应,那么它们就会启动,但如果它们没有响应那么它们就会失效。如果他们没有回复10次重试,我认为他们已经死了,这意味着如果他们没有回应,我会重试10次。

现在我需要在for循环中并行迭代hostnames列表,所以我想出了下面的代码。是否有任何多线程问题或者可以在这里改进什么?我在这里正确使用执行器服务吗?

  private static final ExecutorService executorService = Executors.newFixedThreadPool(20);

  public static void main(String[] args) throws Exception {
    List<String> hostnames = new ArrayList<>();
    //.. populating hostnames

    List<Future<Void>> futures = new ArrayList<Future<Void>>();
    for (final String machine : hostnames) {
      Callable<Void> callable = new Callable<Void>() {
        public Void call() throws Exception {
          String url = "http://" + machine + ":8080/ruok";
          if (!checkServer(url)) {
            System.out.println("server down: " + machine);
          }
          return null;
        }
      };
      futures.add(executorService.submit(callable));
    }
    executorService.shutdown();
    for (Future<Void> future : futures) {
      future.get();
    }
    System.out.println("All done!");
  }

  private static boolean checkServer(final String url) {
    boolean isUp = false;
    int retry = 10;
    for (int i = 1; i <= retry; i++) {
      try {
        RestClient.getInstance().getClient().getForObject(url, String.class);
        isUp = true;
        break;
      } catch (Exception ex) {
        // log exception
      }
    }
    return isUp;
  }

0 个答案:

没有答案