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•10mo ago

Comments

Neywiny•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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•10mo 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";
  }

Running Tesla Model 3's computer on my desk using parts from crashed cars

https://bugs.xdavidhu.me/tesla/2026/03/23/running-tesla-model-3s-computer-on-my-desk-using-parts-...
437•driesdep•6h ago•126 comments

ARC-AGI-3

https://arcprize.org/arc-agi/3
297•lairv•9h ago•189 comments

False claims in a widely-cited paper

https://statmodeling.stat.columbia.edu/2026/03/24/false-claims-in-a-published-no-corrections-no-c...
181•qsi•3h ago•60 comments

My astrophotography in the movie Project Hail Mary

https://rpastro.square.site/s/stories/phm
752•wallflower•3d ago•189 comments

Two studies in compiler optimisations

https://www.hmpcabral.com/2026/03/20/two-studies-in-compiler-optimisations/
27•hmpc•3d ago•0 comments

Earthquake scientists reveal how overplowing weakens soil at experimental farm

https://www.washington.edu/news/2026/03/19/earthquake-scientists-reveal-how-overplowing-weakens-s...
124•Brajeshwar•13h ago•49 comments

Show HN: Nit – I rebuilt Git in Zig to save AI agents 71% on tokens

https://justfielding.com/blog/nit-replacing-git-with-zig
18•fielding•52m ago•9 comments

The EU still wants to scan your private messages and photos

https://fightchatcontrol.eu/?foo=bar
808•MrBruh•7h ago•221 comments

90% of Claude-linked output going to GitHub repos w <2 stars

https://www.claudescode.dev/?window=since_launch
217•louiereederson•9h ago•126 comments

My DIY FPGA board can run Quake II

https://blog.mikhe.ch/quake2-on-fpga/part4.html
85•sznio•3d ago•30 comments

Supreme Court Sides with Cox in Copyright Fight over Pirated Music

https://www.nytimes.com/2026/03/25/us/politics/supreme-court-cox-music-copyright.html
302•oj2828•13h ago•243 comments

"Disregard That" Attacks

https://calpaterson.com/disregard.html
30•leontrolski•4h ago•11 comments

Apple randomly closes bug reports unless you "verify" the bug remains unfixed

https://lapcatsoftware.com/articles/2026/3/11.html
324•zdw•8h ago•178 comments

Quantization from the Ground Up

https://ngrok.com/blog/quantization
213•samwho•12h ago•43 comments

Show HN: A plain-text cognitive architecture for Claude Code

https://lab.puga.com.br/cog/
46•marciopuga•4h ago•19 comments

The truth that haunts the Ramones: 'They sold more T-shirts than records'

https://english.elpais.com/culture/2026-03-17/the-uncomfortable-truth-that-will-always-haunt-the-...
27•c420•4d ago•3 comments

Woman who never stopped updating her lost dog's chip reunites with him after 11y

https://www.cbc.ca/radio/asithappens/11-year-dog-reunion-9.7140780
119•gnabgib•4h ago•65 comments

Show HN: Optio – Orchestrate AI coding agents in K8s to go from ticket to PR

https://github.com/jonwiggins/optio
28•jawiggins•10h ago•18 comments

Miscellanea: The War in Iran

https://acoup.blog/2026/03/25/miscellanea-the-war-in-iran/
463•decimalenough•23h ago•665 comments

Rendering complex scripts in terminal and OSC 66

https://thottingal.in/blog/2026/03/22/complex-scripts-in-terminal/
19•sthottingal•3d ago•3 comments

Thoughts on slowing the fuck down

https://mariozechner.at/posts/2026-03-25-thoughts-on-slowing-the-fuck-down/
727•jdkoeck•14h ago•349 comments

Jury finds Meta liable in case over child sexual exploitation on its platforms

https://www.cnn.com/2026/03/24/tech/meta-new-mexico-trial-jury-deliberation
326•billfor•1d ago•441 comments

VitruvianOS – Desktop Linux Inspired by the BeOS

https://v-os.dev
346•felixding•1d ago•205 comments

FreeCAD v1.1

https://blog.freecad.org/2026/03/25/freecad-version-1-1-released/
196•sho_hn•8h ago•60 comments

The Mystery of Rennes-Le-Château, Part 1: The Priest's Treasure

https://www.filfre.net/2026/03/the-mystery-of-rennes-le-chateau-part-1-the-priests-treasure/
14•ibobev•2d ago•0 comments

Sodium-ion EV battery breakthrough delivers 11-min charging and 450 km range

https://electrek.co/2026/03/25/sodium-ion-ev-battery-delivers-11-min-charging-450-km-range/
136•breve•7h ago•93 comments

Updates to GitHub Copilot interaction data usage policy

https://github.blog/news-insights/company-news/updates-to-github-copilot-interaction-data-usage-p...
252•prefork•8h ago•119 comments

I tried to prove I'm not AI. My aunt wasn't convinced

https://www.bbc.com/future/article/20260324-i-tried-to-prove-im-not-an-ai-deepfake
146•dabinat•17h ago•164 comments

Health NZ staff told to stop using ChatGPT to write clinical notes

https://www.rnz.co.nz/news/national/590645/health-nz-staff-told-to-stop-using-chatgpt-to-write-cl...
120•billybuckwheat•7h ago•40 comments

Antimatter has been transported for the first time

https://www.nature.com/articles/d41586-026-00950-w
371•leephillips•13h ago•167 comments