Issue
Is there a java equivalent of the following asynch/await .NET 4.5 code to handle httprequests or really any invoked method call)?
public async Task<System.IO.TextReader> DoRequestAsync(string url)
{
HttpWebRequest req = HttpWebRequest.CreateHttp(url);
req.AllowReadStreamBuffering = true;
var tr = await DoRequestAsync(req); // <- Wait here and even do some work if you want.
doWorkWhilewaiting(); // ...look ma' no callbacks.
return tr;
}
I was planning on calling this within a controller /GET method (to get data from 3rd partyl REST endpoint) and I'm completely new to the java world.
Any information is greatly appreciated.
Solution
No, Java doesn't have anything like async/await. The java.util.concurrent
package contains various helpful classes around concurrency (for thread pools, producer/consumer queues etc) but really it's the language support in C# 5 that ties everything together... and that's just not present in Java yet.
It's not part of the plans for Java 8 either, as far as I can tell - although things like method literals and lambda expressions will at least make the explicit callback approach a lot simpler than it is in Java 7.
Answered By - Jon Skeet