Search code examples
javamultithreadingasynchronoussynchronous

What is the difference between asynchronous with waiting for result and synchronous?


Recently, I am learning multi-threading and asynchronous programing in java, while I found this confusing.

To be clear about my question: Are the codes below equivalent?

  • If no, why? In my opinion, in the first snippet, the while loop will keep the original thread busy (meaning blocking?).

  • If yes, how to use asynchronous properly?

//asynchronous programing

ExecutorService threadpool = Executors.newCachedThreadPool();
Future<Long> futureTask = threadpool.submit(() -> factorial(number));

while (!futureTask.isDone()) {
    System.out.println("FutureTask is not finished yet..."); 
} 
long result = futureTask.get(); 

threadpool.shutdown();
//synchronous
long result = factorial(number)

Solution

  • When tasks are to be executed one after the other, using asynchronous methods does not really make sense: you lose the overhead of synchronization and still have to wait for the end of the processing. Furthermore, if you use an active loop to wait for the end:

    while (!futureTask.isDone()) {   // active wait loop
        System.out.println("FutureTask is not finished yet..."); 
    } 
    

    you add even more load to the system. At least you should use a wait method to put the current thread in a suspended mode until the other processing is finished.

    But anyway, if tasks are to be executed one after the other, just call them synchronously one after the other:

    factorial(number));
    other processings...
    

    It leads to cleaner and simpler to maintain code, with no performance loss.