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.

Building an HTML-first site doubled our users overnight

https://mohkohn.co.uk/writing/html-first/
393•edent•2h ago•162 comments

AMA: I'm Eric Ries (The Lean Startup) & Author of New Bestseller Incorruptible

61•eries•52m ago•44 comments

PgDog is funded and coming to a database near you

https://pgdog.dev/blog/our-funding-announcement
88•levkk•1h ago•53 comments

Apache Burr: Build reliable AI agents and applications

https://burr.apache.org/
16•anhldbk•39m ago•1 comments

Mercedes‑Benz starts large‑scale production of electric axial flux motor

https://media.mercedes-benz.com/en/article/bebac2af-acdc-465a-9538-adb0bf3d8ccf
336•raffael_de•7h ago•191 comments

All 9,300 Japanese train station, animated by the year it opened (1872–2026)

https://jivx.com/eki
85•momentmaker•3h ago•32 comments

macOS Container Machines

https://github.com/apple/container/blob/main/docs/container-machine.md
1024•timsneath•15h ago•355 comments

Claude Fable 5

https://www.anthropic.com/news/claude-fable-5-mythos-5
2455•Philpax•22h ago•1944 comments

Buy a train, bridge or tracks from the Swiss Railway

https://sbbresale.ch/
92•kisamoto•2d ago•49 comments

A €0.01 bank transfer could compromise a banking AI agent

https://blue41.com/blog/how-we-helped-bunq-secure-their-financial-ai-assistant/
42•tvissers•2h ago•18 comments

Who Runs Your Rust Future? Hands-On Intro to Async Rust

https://aibodh.com/posts/async-rust-chapter-1-hands-on-intro-to-async-rust/
50•febin•2d ago•4 comments

The iPad was on Tailscale: a WebRTC debugging story

https://p2claw.com/blog/2026-06-09-the-ipad-was-on-tailscale/
5•syllogistic•27m ago•0 comments

'They take you out of life, out of time': a journey into Spain's cave paintings

https://www.theguardian.com/science/2026/jun/02/journey-into-spain-palaeolithic-cave-paintings-al...
18•NaOH•1d ago•3 comments

AWS Bedrock to require sharing data with Anthropic for Mythos and future models

285•TomAnthony•7h ago•183 comments

Reviving Papers with Code

https://paperswithcode.co/
127•nielz_r•2d ago•27 comments

Hacking for Defense Stanford 2026 – Lessons Learned Presentations

https://steveblank.com/2026/06/08/g-for-defense-stanford-2026-lessons-learned-presentations/
57•sblank•1d ago•28 comments

Smudging the game disc to make speedrunning 'SpongeBob' faster

https://www.inverse.com/input/gaming/the-dirty-secret-that-makes-speedrunning-on-spongebob-a-lot-...
7•pncnmnp•13h ago•1 comments

I Hate (Most) Keyboard 'Fn' Keys

https://danq.me/2026/06/09/fn-keys/
127•speckx•2h ago•130 comments

Upcoming breaking changes for npm v12

https://github.blog/changelog/2026-06-09-upcoming-breaking-changes-for-npm-v12/
443•plasma•18h ago•180 comments

Magnetoelectric antennas could transform how underwater robots talk

https://newatlas.com/engineering/magnetoelectric-antennas-submarine-robots-communications/
55•breve•3d ago•22 comments

Rich Sutton on AI creativity and discovery

https://twitter.com/RichardSSutton/status/2061216087744946656
184•yimby•13h ago•94 comments

German ruling declares Google liable for false answers in AI Overviews

https://the-decoder.com/landmark-german-ruling-declares-googles-ai-overviews-are-googles-own-word...
824•ahlCVA•13h ago•461 comments

RIP software hackathons. Long live the hardware hackathon

https://blog.oscars.dev/posts/rip-software-hackathons-long-live-the-hardware-hackathon/
242•ozcap•17h ago•116 comments

Notes on DeepSeek

https://twitter.com/NikoMcCarty/status/2064686557400100884
53•vinhnx•1h ago•35 comments

Surprise, pay $1000

https://forestwalk.ai/blog/surprise-blacksmith-costs/
292•apike•17h ago•137 comments

Show HN: macOS menu bar gauges for your Claude Code quota

https://github.com/grzegorz-raczek-unit8/claude-quota
46•grzracz•5h ago•31 comments

What it feels like to work with Mythos

https://www.oneusefulthing.org/p/what-it-feels-like-to-work-with-mythos
338•swolpers•22h ago•300 comments

Ultrafast machine learning on FPGAs via Kolmogorov-Arnold Networks

https://aarushgupta.io/posts/kan-fpga/
267•ag2718•20h ago•45 comments

I thought I knew how electrolysis worked [video]

https://www.youtube.com/watch?v=eq7fR9ISuCw
86•tambourine_man•5d ago•10 comments

OpenCV 5 Is Here: The Biggest Leap in Years for Computer Vision

https://opencv.org/opencv-5/
805•ternaus•4d ago•143 comments