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

Comments

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

I Ported Mac OS X to the Nintendo Wii

https://bryankeller.github.io/2026/04/08/porting-mac-os-x-nintendo-wii.html
141•blkhp19•57m ago•23 comments

Muse Spark – Meta Superintelligence Labs

https://meta.ai/
55•snowman647•31m ago•12 comments

Git commands I run before reading any code

https://piechowski.io/post/git-commands-before-reading-code/
1085•grepsedawk•7h ago•244 comments

MegaTrain: Full Precision Training of 100B+ Parameter LLMs on a Single GPU

https://arxiv.org/abs/2604.05091
152•chrsw•4h ago•35 comments

The Future of Everything Is Lies, I Guess

https://aphyr.com/posts/411-the-future-of-everything-is-lies-i-guess
105•pabs3•3h ago•56 comments

They're Made Out of Meat (1991)

http://www.terrybisson.com/theyre-made-out-of-meat-2/
157•surprisetalk•5h ago•50 comments

Muse Spark: Scaling Towards Personal Superintelligence

https://ai.meta.com/blog/introducing-muse-spark-msl/?_fb_noscript=1
22•chabons•35m ago•8 comments

Veracrypt project update

https://sourceforge.net/p/veracrypt/discussion/general/thread/9620d7a4b3/
802•super256•9h ago•298 comments

Škoda DuoBell: A bicycle bell that penetrates noise-cancelling headphones

https://www.skoda-storyboard.com/en/skoda-world/skoda-duobell-a-bicycle-bell-that-outsmarts-even-...
318•ra•7h ago•413 comments

US cities are axing Flock Safety surveillance technology

https://www.cnet.com/home/security/when-flock-comes-to-town-why-cities-are-axing-the-controversia...
333•giuliomagnifico•4h ago•170 comments

Microsoft Abruptly Terminates VeraCrypt Account, Halting Windows Updates

https://www.404media.co/microsoft-abruptly-terminates-veracrypt-account-halting-windows-updates/
114•donohoe•1h ago•15 comments

Show HN: Explore the Silk Roads through an interactive map

https://www.intofarlands.com/silk-roads-map
25•intofarlands•1h ago•2 comments

Audio Reactive LED Strips Are Diabolically Hard

https://scottlawsonbc.com/post/audio-led
125•surprisetalk•1d ago•37 comments

Project Glasswing: Securing critical software for the AI era

https://www.anthropic.com/glasswing
1443•Ryan5453•22h ago•753 comments

Show HN: Go-Bt: Minimalist Behavior Trees for Go

https://github.com/rvitorper/go-bt
20•rvitorper•2h ago•1 comments

Revision Demoparty 2026: Razor1911 [video]

https://www.youtube.com/watch?v=Lw4W9V57SKs&t=5716s
285•tetrisgm•11h ago•96 comments

Lunar Flyby

https://www.nasa.gov/gallery/lunar-flyby/
889•kipi•1d ago•216 comments

Teardown of unreleased LG Rollable shows why rollable phones aren't a thing

https://arstechnica.com/gadgets/2026/04/teardown-of-unreleased-lg-rollable-shows-why-rollable-pho...
20•DamnInteresting•1d ago•11 comments

Your File System Is Already A Graph Database

https://rumproarious.com/2026/04/04/your-file-system-is-already-a-graph-database/
106•alxndr•2d ago•51 comments

Show HN: We built a camera only robot vacuum for less than 300$ (Well almost)

https://indraneelpatil.github.io/blog/2026/robot-vacuum/
81•indraneelpatil•2d ago•34 comments

Protect your shed

https://dylanbutler.dev/blog/protect-your-shed/
253•baely•13h ago•68 comments

Virtual Mars Traverse: Every inch of Curiosity rover's path since 2012 landing

https://www.rovers.land/
14•bookofjoe•3d ago•2 comments

Show HN: I pipe free sports streams into Jellyfin – no ads, just HLS

https://github.com/pcruz1905/hls-restream-proxy
48•pruz•4h ago•9 comments

Iran demands Bitcoin fees for ships passing Hormuz during ceasefire

https://www.ft.com/content/02aefac4-ea62-48db-9326-c0da373b11b8
58•pavlov•2h ago•78 comments

System Card: Claude Mythos Preview [pdf]

https://www-cdn.anthropic.com/53566bf5440a10affd749724787c8913a2ae0841.pdf
793•be7a•22h ago•588 comments

Show HN: BAREmail ʕ·ᴥ·ʔ – minimalist Gmail client for bad WiFi

https://github.com/matt-virgo/baremail
11•Virgo_matt•1h ago•6 comments

Mario and Earendil

https://lucumr.pocoo.org/2026/4/8/mario-and-earendil/
49•doppp•7h ago•23 comments

GLM-5.1: Towards Long-Horizon Tasks

https://z.ai/blog/glm-5.1
589•zixuanlimit•1d ago•239 comments

Show HN: I built a navigation app that displays weather along the route

https://navimodo.com/
5•vkatluri•2d ago•4 comments

Cambodia unveils statue to honour famous landmine-sniffing rat

https://www.bbc.com/news/articles/c0rx7xzd10xo
465•speckx•23h ago•108 comments