Java Executors run multiple tasks and process the first result

Description

Java Executors run multiple tasks and process the first result


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class TaskValidator implements Callable<String> {
  private String user;
  private String password;

  public TaskValidator(String user, String password) {
    this.user = user;
    this.password = password;
  }/*from  w  w w . j a v a  2s.c  om*/

  @Override
  public String call() throws Exception {
    System.out.println("The user has been found: " + user);
    Thread.sleep(2000);//you can sleep random seconds
    return user;
  }

}

public class Main {
  public static void main(String[] args) {
    String username = "test";
    String password = "test";

    TaskValidator ldapTask = new TaskValidator(username, password);
    TaskValidator dbTask = new TaskValidator(username, password);

    List<TaskValidator> taskList = new ArrayList<>();
    taskList.add(ldapTask);
    taskList.add(dbTask);

    ExecutorService executor = (ExecutorService) Executors.newCachedThreadPool();
    String result;
    try {
      result = executor.invokeAny(taskList);
      System.out.println("Main: Result: " + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    executor.shutdown();
  }
}



PreviousNext

Related