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

SPEAKE(a)R: Turn Speakers to Microphones for Fun and Profit [pdf] (2017)

https://www.usenix.org/system/files/conference/woot17/woot17-paper-guri.pdf
33•Eridanus2•1h ago•15 comments

Game Devs Explain the Tricks Involved with Letting You Pause a Game

https://kotaku.com/video-game-devs-explain-how-pausing-works-and-sometimes-it-gets-weird-2000686339
109•speckx•2d ago•80 comments

NIST scientists create 'any wavelength' lasers

https://www.nist.gov/news-events/news/2026/04/any-color-you-nist-scientists-create-any-wavelength...
310•rbanffy•13h ago•134 comments

What are skiplists good for?

https://antithesis.com/blog/2026/skiptrees/
77•mfiguiere•1d ago•18 comments

Anonymous request-token comparisons from Opus 4.6 and Opus 4.7

https://tokens.billchambers.me/leaderboard
519•anabranch•17h ago•509 comments

College instructor turns to typewriters to curb AI-written work

https://sentinelcolorado.com/uncategorized/a-college-instructor-turns-to-typewriters-to-curb-ai-w...
281•gnabgib•15h ago•272 comments

The electromechanical angle computer inside the B-52 bomber's star tracker

https://www.righto.com/2026/04/B-52-star-tracker-angle-computer.html
335•NelsonMinar•17h ago•91 comments

Updating Gun Rocket through 10 years of Unity Engine

https://jackpritz.com/blog/updating-gun-rocket-through-10-years-of-unity-engine
82•tyleo•2d ago•32 comments

Why Japan has such good railways

https://worksinprogress.co/issue/why-japan-has-such-good-railways/
412•RickJWagner•21h ago•377 comments

Binary Dependencies: Identifying the Hidden Packages We All Depend On

https://vlad.website/binary-dependencies-identifying-the-hidden-packages-we-all-depend-on/
19•PaulHoule•2d ago•2 comments

Keep Pushing: We Get 10 More Days to Reform Section 702

https://www.eff.org/deeplinks/2026/04/keep-pushing-we-get-10-more-days-reform-section-702
62•nobody9999•2h ago•4 comments

The world in which IPv6 was a good design

https://apenwarr.ca/log/20170810
53•signa11•7h ago•12 comments

SI Units for Request Rate (2024)

https://entropicthoughts.com/si-units-for-request-rate
70•fanf2•3d ago•45 comments

State of Kdenlive

https://kdenlive.org/news/2026/state-2026/
401•f_r_d•22h ago•123 comments

Modern Common Lisp with FSet

https://fset.common-lisp.dev/Modern-CL/Top_html/index.html
156•larve•3d ago•18 comments

Zero-Copy GPU Inference from WebAssembly on Apple Silicon

https://abacusnoir.com/2026/04/18/zero-copy-gpu-inference-from-webassembly-on-apple-silicon/
82•agambrahma•11h ago•31 comments

Migrating from DigitalOcean to Hetzner

https://isayeter.com/posts/digitalocean-to-hetzner-migration/
781•yusufusta•20h ago•394 comments

Optimizing Ruby Path Methods

https://byroot.github.io/ruby/performance/2026/04/18/faster-paths.html
101•weaksauce•13h ago•36 comments

Metatextual Literacy

https://www.jenn.site/metatextual-literacy/
30•dado3212•3d ago•3 comments

Dizzying Spiral Staircase with Single Guardrail Once Led to Top of Eiffel Tower

https://www.smithsonianmag.com/smart-news/a-dizzying-spiral-staircase-with-a-single-guardrail-onc...
26•bookofjoe•2d ago•12 comments

It's cool to care (2025)

https://alexwlchan.net/2025/cool-to-care/
8•surprisetalk•3d ago•6 comments

William Cecil's Succession Plan

https://www.historytoday.com/archive/history-matters/william-cecils-succession-plan
6•Petiver•4d ago•0 comments

Thoughts and feelings around Claude Design

https://samhenri.gold/blog/20260418-claude-design/
307•cdrnsf•14h ago•197 comments

Sumida Aquarium Posts 2026 Penguin Relationship Chart, with Drama and Breakups

https://www.sumida-aquarium.com/special/sokanzu/en/2026/
215•Lwrless•3d ago•11 comments

Bypassing the kernel for 56ns cross-language IPC

https://github.com/riyaneel/Tachyon/tree/main/docs/adr
43•riyaneel•2d ago•20 comments

Show HN: MDV – a Markdown superset for docs, dashboards, and slides with data

https://github.com/drasimwagan/mdv
115•drasim•18h ago•43 comments

My first impressions on ROCm and Strix Halo

https://blog.marcoinacio.com/posts/my-first-impressions-rocm-strix-halo/
44•random_•12h ago•34 comments

Scientists discover “cleaner ants” that groom giant ants in Arizona desert

https://www.sciencedaily.com/releases/2026/04/260414075641.htm
105•t-3•3d ago•38 comments

NASA Shuts Off Instrument on Voyager 1 to Keep Spacecraft Operating

https://science.nasa.gov/blogs/voyager/2026/04/17/nasa-shuts-off-instrument-on-voyager-1-to-keep-...
175•sohkamyung•10h ago•78 comments

Understanding the FFT Algorithm (2013)

https://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/
93•peter_d_sherman•4d ago•10 comments