有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java并行迭代for循环中的所有机器,并检查它们是启动还是关闭?

我有一个ArrayList中的机器列表。我正在检查所有这些机器是否都在运行,因此我正在对它们进行http调用,如果它们响应,则它们处于运行状态,但如果它们没有响应,则它们处于停机状态。我认为如果他们10次没有响应,他们就死了,这意味着如果他们没有响应,每台机器我会重试10次

现在我需要在for循环中并行迭代hostnames列表,因此我产生了以下代码。这里是否存在多线程问题或任何可以改进的地方?我在这里正确使用executor服务吗

  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) 个答案