I had similar requirement. On a specific operation, I had to call some set of validator methods which in-turn validates certain components. Every validator used to take certain amount of time and had to reduce it and decided to call it in async.
Indeed there are many ways to achieve it, this is one of the approach which I solved.
Since validators mostly doesn't return any values, took advantage of Runnable class lambda. In below example addition
, multiply
and subtraction
methods will be invoked asynchronously and in parallel.
public class MultiThreading {
public static void addition() {
System.out.println("Addition");
}
public static void multiply() {
System.out.println("multiplication");
}
public static void subtraction() {
System.out.println("subtraction");
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Runnable callMultiply = () -> multiply(); //Create Runnable reference using lambda
executor.execute(callMultiply);
executor.execute(() -> addition()); //inline
executor.execute(() -> subtraction());
executor.shutdown();
}
}