5

Im a c# developer and now started transitioning to Java...and started comparing the features

i came across this Future in Java concurrency https://docs.oracle.com/javaee/6/tutorial/doc/gkkqg.html As per the documentation example it says Even if the payment processor takes a long time, the client can continue working, and display the result when the processing finally completes.

So can we assume Future is same as c# async await..if not please lemme know the difference...

As per my knowledge sync ,await i have used in mobile operations where we didnt want the UI thread to be blocked while it interacts with apis or service.

shiv455
  • 7,384
  • 19
  • 54
  • 93

2 Answers2

3

Future is just an interface. It is not capable of handling anything asynchronously by itself. You receive a Future object when you submit some work to be executed asynchronously in an ExecutorService. Use Future.get() to block the current thread until the result is ready. Of course you should do something useful in the current thread between the time you submit the work and try to get the result.

mvd
  • 2,596
  • 2
  • 33
  • 47
  • if it blocks the main thread then howcome the call becomes asynchronous.please correct me if im wrong.. – shiv455 Nov 09 '15 at 20:48
  • And the doc says "the client can continue working, and display the result when the processing finally completes" – shiv455 Nov 09 '15 at 20:55
  • 2
    The call only becomes asynchronous because when you hand off the work (Callable) to an ExecutorService, it is executed in another thread. – mvd Nov 09 '15 at 21:08
0

Java Future is not equivalent to C# async/await. Simply it is the result of an asynchronous task (running in a different thread) that can be awaited in the main thread. When calling a method returning Future, that method will be executed in a different thread and when the result is needed in the caller thread you can block that thread with Future.get().

While C# async/await doesn't imply using a different thread. It only suspends the enclosing method and returns the execution to the caller method where both methods can be executed in the same thread.

AlHassan
  • 41
  • 1
  • 7