Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 299 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Java Equivalent of C# async/await?

#1
I am a normal C# developer but occasionally I develop application in Java. I'm wondering if there is any Java equivalent of C# async/await?
In simple words what is the java equivalent of:

async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
var urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
return urlContents.Length;
}
Reply

#2
No, there isn't any equivalent of async/await in Java - or even in C# before v5.

It's a fairly complex language feature to build a state machine behind the scenes.

There's relatively little *language* support for asynchrony/concurrency in Java, but the `java.util.concurrent` package contains a lot of useful *classes* around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)
Reply

#3
Java itself has no equivalent features, but third-party libraries exist which offer similar functionality, e.g.[Kilim][1].


[1]:

[To see links please register here]

Reply

#4
There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a [CountDownLatch][1]. You *could* then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).

Using this however inside your application as opposed to your test is **NOT** what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.


[1]:

[To see links please register here]

Reply

#5
**async** and **await** are syntactic sugars. The essence of async and await is state machine. The compiler will transform your async/await code into a state machine.

At the same time, in order for async/await to be really practicable in real projects, we need to have lots of **Async I/O library functions** already in place. For C#, most original synchronized I/O functions has an alternative Async version. The reason we need these Async functions is because in most cases, your own async/await code will boil down to some library Async method.

The Async version library functions in C# is kind of like the AsynchronousChannel concept in Java. For example, we have AsynchronousFileChannel.read which can either return a Future or execute a callback after the read operation is done. But it’s not exactly the same. All C# Async functions return Tasks (similar to Future but more powerful than Future).

So let’s say Java do support async/await, and we write some code like this:

public static async Future<Byte> readFirstByteAsync(String filePath) {
Path path = Paths.get(filePath);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);

ByteBuffer buffer = ByteBuffer.allocate(100_000);
await channel.read(buffer, 0, buffer, this);
return buffer.get(0);
}

Then I would imagine the compiler will transform the original async/await code into something like this:

public static Future<Byte> readFirstByteAsync(String filePath) {

CompletableFuture<Byte> result = new CompletableFuture<Byte>();

AsyncHandler ah = new AsyncHandler(result, filePath);

ah.completed(null, null);

return result;
}
And here is the implementation for AsyncHandler:

class AsyncHandler implements CompletionHandler<Integer, ByteBuffer>
{
CompletableFuture<Byte> future;
int state;
String filePath;

public AsyncHandler(CompletableFuture<Byte> future, String filePath)
{
this.future = future;
this.state = 0;
this.filePath = filePath;
}

@Override
public void completed(Integer arg0, ByteBuffer arg1) {
try {
if (state == 0) {
state = 1;
Path path = Paths.get(filePath);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);

ByteBuffer buffer = ByteBuffer.allocate(100_000);
channel.read(buffer, 0, buffer, this);
return;
} else {
Byte ret = arg1.get(0);
future.complete(ret);
}

} catch (Exception e) {
future.completeExceptionally(e);
}
}

@Override
public void failed(Throwable arg0, ByteBuffer arg1) {
future.completeExceptionally(arg0);
}
}

Reply

#6
I make and released Java async/await library.

[To see links please register here]


This library don't need compiler extension, and realize stackless IO processing in Java.

async Task<int> AccessTheWebAsync(){
HttpClient client= new HttpClient();
var urlContents= await client.GetStringAsync("http://msdn.microsoft.com");
  return urlContents.Length;
}
   ↓

//LikeWebApplicationTester.java
BlockingQueue<Integer> AccessTheWebAsync() {
HttpClient client = new HttpClient();
return awaiter.await(
() -> client.GetStringAsync("http://msdn.microsoft.com"),
urlContents -> {
return urlContents.length();
});
}
public void doget(){
BlockingQueue<Integer> lengthQueue=AccessTheWebAsync();
awaiter.awaitVoid(()->lengthQueue.take(),
length->{
System.out.println("Length:"+length);
}
);
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through