frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Understanding Java's Asynchronous Journey

https://amritpandey.io/understanding-javas-asynchronous-journey/
17•hardasspunk•5mo ago

Comments

Neywiny•5mo ago
I don't get it. The first example in JS vs Java looks very similar. Now all those other code blocks, they certainly have more going on but idk how that compares to JS. And to answer the questions:

A completable future is something that in the future may complete. I think that's self explanatory. A promise seems equally vague.

Boilerplate looks the same. JS is just a function, Java they put a class around it. Java requires exception handling which is annoying but having fought errors in async JS, I'll take all I can get.

API is eh. Sure. But that's not even shown in this example so I have no idea.

So JS saves like 3 lines? Is that really so much better?

cogman10•5mo ago
> A completable future is something that in the future may complete. I think that's self explanatory.

But not the reason for the name :).

It's called "completable" because these futures have a method on them `future.complete("value")`. Before their introduction, there was a `Future` API that java had.

nogridbag•5mo ago
Yeah that first example is rather poor. And it uses the word boilerpate to seemingly refer to the stuff unrelated to the async code (class declaration, exception handling, main method).

I don't use Java async much, but I guess if you have a utility method named "setTimeout" than the example can simply be:

    public CompletableFuture<String> fetchData() {
        return setTimeout(() -> "Data Fetched", 10000);
    }

    public void loadData() {
        fetchData().thenAccept(System.out::println);
    }
Which is simpler or equivalent to the JS example.
stevoski•5mo ago
The Java 1 example uses lambdas, which were introduced in Java 8.

It’s probably intentional, because it allows showing the Java 1 Thread approach succinctly.

But as long-term Java person, I find it jarring.

philipwhiuk•5mo ago
Java's had `var` since Java 10 but apparently the author deliberately ignored that to make the example as wordy as possible.

It's a little tiring to read a Java example with an entry-point (the public-static-void bit) and then a JavaScript example without one.

If you strip that out the original Java is:

  var future = CompletableFuture.supplyAsync(() -> {
        try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Data Fetched";
        });
  future.thenAccept(result -> System.out.println(result));
  System.out.println("Prints first"); // prints before the async result
which is only obtuse due to checked exceptions.

Arguably it's still a different thing you're doing, because it's not scheduling a task on a pool, it's creating a thread which sleeps for 10 seconds.

elric•5mo ago
`var` is very unhelpful in situations where the reader might not be entirely familiar with the context, especially when using factory methods.

I don't think the author was trying to make the example "wordy" so much as "clear".

cogman10•5mo ago
Also, arguably, the wrong way to do something like this.

The author uses `setTimeout` for javascript. The equivalent for Java is either the `Timer` class or a `ScheduledExecutorService`. Doing a `Thread.sleep` simply isn't how you should approach this.

With that in mind, if you want to use both these things and keep the completable future interface you'd have to do soemthing like this.

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    var future = new CompletableFuture<String>();
    scheduler.schedule(()->future.complete("Data Fetched"), 10, TimeUnit.SECONDS);
    future.thenAccept(result -> System.out.println(result));
    System.out.println("Prints first"); // prints before the async result
    scheduler.shutdown();
wpollock•5mo ago
In Java 24, new features support educational and demonstration use. You don't need a class to wrap your main method, which also has a simpler signature. To compare JavaScript with Java examples, one should make use of these features.

While the examples may need some work, I enjoyed this post, it nicely shows the evolution of Java concurrency.

AtlasBarfed•5mo ago
Does no.js still limit you to a single core/CPU use?

Or as a node successfully been able to start utilizing more cores underneath its JavaScript single thread model. It presents the programmer?

I just remember early node.js from like 15 years ago and the single background task limitation of JavaScript running in a web page.

Cuz you got async code is nice, but what you really wanted to be able to harness in modern CPUs is multi-core

That said, I've been looking for an article like this for a while, although I think there are other associated libraries that also had steps in here. I do think the jvm adopted a lot of those, but I'm not sure if they actually are better than the original extension libraries.

msgilligan•5mo ago
I simplified the first example to:

  void main() {
      CompletableFuture<String> future = CompletableFuture.supplyAsync(this::asyncMethod);
      future.thenAccept(result -> IO.println(result));
      IO.println("Prints first");             // prints before the async result
      future.join();                          // Wait for future to complete
  }

  String asyncMethod() {
      try {
          Thread.sleep(10000);
      } catch (InterruptedException e) {
          return "Interrupted";
      }
      return "Data Fetched";
  }
I made the following changes:

1. Move the asynchronous function called in the CompletableFuture to its own method

2. Use Java 25 "instance main method" (see JEP 25: https://openjdk.org/jeps/512)

3. Use Java 25 IO.println() to simplify console output

4. Instead of throwing a fatal exception on interruption, return "Interrupted" immediately.

5. Use future.join() so the main method waits for the future to complete and the "Data fetched" output is printed.

This program can be run directly from source with `java Example.java`. (If you're using Java 24 or a version of Java 25 prior to EA 22, you need to use `java --enable-preview Example.java`)

Here is a modified version of the example that interrupts the thread:

  void main() {
      ExecutorService executor = Executors.newSingleThreadExecutor();
      CompletableFuture<String> future = CompletableFuture.supplyAsync(this::asyncMethod, executor);
      future.thenAccept(result -> IO.println(result));
      IO.println("Prints first");             // prints before the async result
      executor.shutdownNow();
      future.join();                          // Wait for future to complete
  }

  String asyncMethod() {
      try {
          Thread.sleep(10000);
      } catch (InterruptedException e) {
          return "Interrrupted";
      }
      return "Data Fetched";
  }

New-hire air traffic controllers must be under age of 31

https://www.faa.gov/air-traffic-controller-qualifications
2•neko_ranger•4m ago•1 comments

Authorities Shut Down Film Festival in New York

https://www.hrw.org/news/2025/11/07/china-authorities-shut-down-film-festival-in-new-york
1•ilamont•7m ago•0 comments

Some Mercedes EVs Now Have a $50k Discount

https://www.carsdirect.com/deals-articles/mercedes-evs-now-have-a-50-000-discount
1•bookofjoe•7m ago•0 comments

UK lawyer buys large numbers of freeholds, sends 'aggressive' payment demands

https://www.sheffieldtribune.co.uk/a-london-lawyer-bought-hundreds-of-sheffield-freeholds-then-th...
1•mrchumphatty•8m ago•0 comments

Ancient earth: a visualization of continental drift. (WebGL)

https://dinosaurpictures.org/ancient-earth
1•fanf2•8m ago•0 comments

Clerk vs. Auth0 vs. Keycloak vs. FusionAuth

https://www.justaftermidnight247.com/insights/clerk-vs-auth0-vs-keycloak-vs-fusionauth/
1•mooreds•8m ago•0 comments

The accidental click that changed everything: the Apify origin story

https://blog.apify.com/apify-origin-story/
1•mooreds•10m ago•0 comments

Ask HN: Is Gemini biased towards Go when asked to pick a programming language?

1•danielfalbo•11m ago•0 comments

Multiprocess Support on Unikraft

https://unikraft.org/blog/2025-05-15-multiprocess
1•mooreds•12m ago•0 comments

Learning the History of Pho

https://www.ace.aaa.com/publications/food-and-drink/history-of-pho.html
1•vinhnx•12m ago•0 comments

Overview of lunar dust toxicity risk [pdf]

https://pmc.ncbi.nlm.nih.gov/articles/PMC9718825/
1•thunderbong•13m ago•0 comments

Cara Cepat Layanan Bws

1•bewsfxdf•16m ago•0 comments

Metaprogramming Acid Test Challenge

https://github.com/7mind/metaprogramming-acid-test
1•pshirshov•16m ago•0 comments

Developer Describes How Roomba Got Its Vacuum

https://spectrum.ieee.org/irobot-roomba-history
2•ripe•21m ago•0 comments

Powering AI at Scale: Benchmarking 1B Vectors in YugabyteDB

https://www.yugabyte.com/blog/benchmarking-1-billion-vectors-in-yugabytedb/
2•ashvardanian•21m ago•0 comments

IRS Direct File won't be available next year

https://apnews.com/article/irs-direct-file-not-available-2026-04f2d0c31bec80b55d122a0e76e08c36
1•bikenaga•21m ago•0 comments

Show HN: I built an HTTP client that perfectly mimics Chrome 142

https://github.com/arman-bd/httpmorph
1•armanified•22m ago•0 comments

AI and the Smartphone Revolution: How U.S. Innovations Are Shaping the Future

https://www.traumen.site/2025/11/ai-and-smartphone-revolution-how-us.html
1•TraumenBlog•27m ago•1 comments

Dr. Benjamin's Fantasy World

https://badfacts.substack.com/p/dr-benjamins-fantasy-world
1•sid_wheat•27m ago•0 comments

Airbus Took Off

https://worksinprogress.co/issue/how-airbus-took-off/
2•Twixes•27m ago•0 comments

DJI Neo 2 Launches in Europe/Canada/Brazil Next Week: U.S. Availability Unlikely

https://dronexl.co/2025/11/08/dji-neo-2-launches-in-europe-canada-and-brazil-next-week-as-u-s-ava...
2•bookofjoe•28m ago•1 comments

I'm calling BS on YC's latest subscription based mosquito killer drone project

https://twitter.com/ycombinator/status/1986917284561207783
1•SchizoDuckie•28m ago•0 comments

Election Day Disinformation: Intimidation, Bots, & Synthetic Voices

https://weaponizedspaces.substack.com/p/election-day-disinformation-intimidation
2•rbanffy•29m ago•0 comments

The enduring power of YouTube comments

https://ra.co/news/83955
2•amadeuspagel•30m ago•0 comments

Early Access for Firefox Support for Organizations

https://blog.mozilla.org/en/firefox/firefox-support-for-organizations/
1•ReadCarlBarks•33m ago•0 comments

Stories, and remains, of Native American children reclaimed from Carlisle school

https://www.pennlive.com/native-american-news/2025/11/stories-and-remains-of-native-american-chil...
1•bikenaga•35m ago•1 comments

Show HN: Avoid Docker builds in GH Actions if the context didn't change

https://github.com/matchory/docker-source-hash-action
1•9dev•36m ago•0 comments

How to give (and get) writing feedback

https://medium.com/hardbound-co/how-to-give-and-get-amazing-writing-feedback-46acb839ecdf
2•cjbarber•37m ago•1 comments

CCP's Fourth Plenum: Priority Industries in China's 15th Five Year Plan

https://twitter.com/neilthomas123/status/1986452637437379067
1•Marshferm•38m ago•0 comments

Join new social media platform

https://aijagarage.com/feed
1•createvideoai•38m ago•0 comments