How it works...

The key of the example is in the Main class. The invokeAny() method of the ThreadPoolExecutor class receives a list of tasks, then launches them, and returns the result of the first task that finishes without throwing an exception. This method returns the same data type that the call() method of the tasks returns. In this case, it returned a String value.

The following screenshot shows the output of an execution of the example when one of the tasks validates the user:

The example has two UserValidator objects that return a random Boolean value. Each UserValidator object is used by a Callable object, implemented by the TaskValidator class. If the validate() method of the UserValidator class returns a false value, the TaskValidator class throws Exception. Otherwise, it returns the true value.

So, we have two tasks that can return the true value or throw Exception. You can have the following four possibilities:

  • Both tasks return the true value. Here, the result of the invokeAny() method is the name of the task that finishes in the first place.
  • The first task returns the true value and the second one throws Exception. Here, the result of the invokeAny() method is the name of the first task.
  • The first task throws Exception and the second one returns the true value. Here, the result of the invokeAny() method is the name of the second task.
  • Both tasks throw Exception. In such a class, the invokeAny() method throws an ExecutionException exception.

If you run the examples several times, you will get each of the four possible solutions.

The following screenshot shows the output of the application when both the tasks throw an exception:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151