frontpage.
newsnewestaskshowjobs

Open Source @Github

fp.

Open in hackernews

Understanding Java's Asynchronous Journey

https://amritpandey.io/understanding-javas-asynchronous-journey/
17•hardasspunk•1y ago

Comments

Neywiny•1y 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•1y 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•1y 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•1y 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•1y 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•1y 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•1y 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();
AtlasBarfed•1y 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•1y 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";
  }
wpollock•1y 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.

AI agent bankrupted their operator while trying to scan DN42

https://lantian.pub/en/article/fun/ai-agent-bankrupted-their-operator-scan-dn42lantian.lantian/
464•xiaoyu2006•4h ago•163 comments

Nobody ever gets credit for fixing problems that never happened (2001) [pdf]

https://web.mit.edu/nelsonr/www/Repenning=Sterman_CMR_su01_.pdf
440•sam_bristow•8h ago•147 comments

If you are asking for human attention, demonstrate human effort

https://tombedor.dev/human-attention-and-human-effort/
673•jjfoooo4•9h ago•214 comments

Show HN: Homebrew 6.0.0

https://brew.sh/2026/06/11/homebrew-6.0.0/
1202•mikemcquaid•19h ago•277 comments

How we made hit video game Prince of Persia

https://www.theguardian.com/culture/2026/jan/05/raiders-of-the-lost-ark-hit-video-game-prince-of-...
105•msephton•2d ago•29 comments

Claude Fable is relentlessly proactive

https://simonwillison.net/2026/Jun/11/fable-is-relentlessly-proactive/
413•lumpa•7h ago•317 comments

Show HN: FablePool – pool money behind a prompt, and Fable builds it in public

https://fablepool.com
384•matthewbarras•11h ago•196 comments

Vinyl succumbs to Loudness War: more than just collateral damage (2025)

https://magicvinyldigital.net/2025/04/27/vinyl-succumbs-to-loudness-war-more-than-just-collateral...
63•sneela•5d ago•79 comments

Digital Sovereignty Becomes an Imperative as the US Reads Dutch Emails

https://www.korte.co/2026/06/11/digital-sovereignty-becomes-an-imparative-as-the-us-reads-dutch-e...
92•dotcoma•3h ago•77 comments

Anthropic apologizes for invisible Claude Fable guardrails

https://www.theverge.com/ai-artificial-intelligence/948280/anthropic-claude-fable-invisible-disti...
413•rarisma•20h ago•381 comments

MiMo Code is now released and open-source

https://mimo.xiaomi.com/mimocode
485•apeters•18h ago•270 comments

Petition to Withdraw Canada's Bill C-22

https://www.ourcommons.ca/petitions/en/Petition/Sign/e-7416
431•hmokiguess•17h ago•144 comments

Removing 'um' from a recording is harder than it sounds

https://doug.sh/posts/erm-a-local-cli-that-strips-ums-uhs-and-erms-from-speech/
72•dougcalobrisi•8h ago•25 comments

macOS 27 Beta breaks the ability to boot Asahi Linux

https://www.phoronix.com/news/macOS-27-Beta-Breaks-Asahi
305•josephcsible•2d ago•127 comments

Ear Training Practice

https://tonedear.com/
235•mattbit•3d ago•98 comments

Claude Fable 5: mid-tier results on coding tasks

https://www.endorlabs.com/learn/claude-fable-5-mythos-grade-hype
313•bugvader•16h ago•148 comments

Software is made between commits

https://zed.dev/blog/introducing-deltadb
255•jeremy_k•16h ago•187 comments

A jacket that harvests drinking water from the air

https://news.utexas.edu/2026/06/11/this-jacket-pulls-drinking-water-from-thin-air/
106•ilreb•9h ago•64 comments

Emacs appearances in pop culture

https://ianyepan.github.io/posts/emacs-in-pop-culture/
323•ggcr•1d ago•88 comments

Lines of code got a better publicist

https://curlewis.co.nz/posts/lines-of-code-got-a-better-publicist/
389•RyeCombinator•20h ago•271 comments

Reading for pleasure is sharply down among schoolkids, report shows

https://www.nbcnews.com/data-graphics/kids-reading-less-lower-levels-department-education-study-r...
156•freejoe76•1d ago•190 comments

Developer gets Half-Life running at 30 FPS on a Nokia N95

https://www.tomshardware.com/video-games/handheld-gaming/developer-gets-half-life-running-at-30-f...
278•ljf•3d ago•91 comments

The RCE that AMD wouldn't fix

https://mrbruh.com/amd2/
267•MrBruh•16h ago•116 comments

Finding Optimal Tokenizers

https://blog.aqnichol.com/2026/06/10/optimal-tokenizers/
22•mcyc•14h ago•0 comments

A Commons of Software Productive Infrastructure, by and for Capital

https://marewolf.me/posts/draupnir/26/software-productive-infrastructure.html
13•simonmic•21h ago•2 comments

WikiLambda the Ultimate

https://en.wikipedia.org/wiki/Wikipedia:Wikipedia_Signpost/2026-05-22/Recent_research
41•Antibabelic•15h ago•6 comments

How Terry Tao became an evangelist for AI in math

https://www.quantamagazine.org/how-terry-tao-became-an-evangelist-for-ai-in-math-20260608/
116•Tomte•3d ago•97 comments

Device Clock Generation (2025)

https://zipcpu.com/blog/2025/12/17/devclk.html
16•mfiguiere•4h ago•2 comments

Apple didn't revolutionize power supplies; new transistors did (2012)

https://www.righto.com/2012/02/apple-didnt-revolutionize-power.html
128•geerlingguy•15h ago•17 comments

Waymo Premier

https://waymo.com/blog/2026/06/waymo-premier/
190•boulos•16h ago•460 comments