int someFunc() {
doA();
doB();
byte data[] = readFromSocket();
return doC(data);
}
int callerFunc() {
doX();
System.out.println(someFunc());
doY();
}
when we invoke the callerFunc() in a virtual thread, it executes till the potentially blocking socket reading, creates a callback or future -like object containing doC(), System.out.println(), doY() - such object is called a "continuation", see "continuation passing style". Then the socket reading is iniitated in an async way, with continuation registered as a callback to be invoked upon completion. Then the native OS thread is freed to do any other work.In javascript approach we would need to manually mark some places `async` and use `await`.
@async
int someFunc() {
doA();
doB();
byte[] data = await readFromSocket();
return doC(data);
}
@async
int callerFunc() {
doX();
System.out.println(await someFunc());
doY();
}
So async / await is a poor man's continuation passing style.
The need to differentiate between 'async' and non 'async' code makes it more difficult to refactor or mix code between 'async' and non 'async' domains.Some people argue that it's better to have the explicit distinction. I personally don't see benefits of this.
Goroutines can wrap code you don't want to block callers, but in practice that get hidden behind APIs that return channels.