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";
  }

NetHack 5.0.0

https://nethack.org/v500/release.html
31•rsaarelm•11m ago•3 comments

Uber wants to turn its drivers into a sensor grid for self-driving companies

https://techcrunch.com/2026/05/01/uber-wants-to-turn-its-millions-of-drivers-into-a-sensor-grid-f...
62•nickvec•2h ago•65 comments

Inventions for battery reuse and recycling increase more than 7-fold in last 10y

https://www.epo.org/en/news-events/news/inventions-battery-reuse-and-recycling-increase-more-seve...
38•JeanKage•2d ago•3 comments

Barman – Backup and Recovery Manager for PostgreSQL

https://github.com/EnterpriseDB/barman
89•nateb2022•3d ago•15 comments

How fast is a macOS VM, and how small could it be?

https://eclecticlight.co/2026/05/02/how-fast-is-a-macos-vm-and-how-small-could-it-be/
185•moosia•8h ago•67 comments

Videolan Dav2d

https://code.videolan.org/videolan/dav2d
8•dabinat•42m ago•0 comments

Why does it take so long to release black fan versions?

https://www.noctua.at/en/expertise/blog/how-can-it-take-so-long-to-release-black-fan-versions
593•buildbot•13h ago•247 comments

Refusal in Language Models Is Mediated by a Single Direction

https://arxiv.org/abs/2406.11717
48•fagnerbrack•4h ago•17 comments

California to begin ticketing driverless cars that violate traffic laws

https://www.bbc.com/news/articles/clypjx3rg2go
9•geox•15m ago•0 comments

Roblox shares plummet 18% as child safety measures weigh on bookings

https://www.cnbc.com/2026/05/01/roblox-rblx-stock-child-safety-earnings.html
24•1vuio0pswjnm7•1h ago•0 comments

AI Self-preferencing in Algorithmic Hiring: Empirical Evidence and Insights

https://arxiv.org/abs/2509.00462
295•laurex•2h ago•145 comments

Why are there both TMP and TEMP environment variables? (2015)

https://devblogs.microsoft.com/oldnewthing/20150417-00/?p=44213
158•ankitg12•9h ago•78 comments

Open Design: Use Your Coding Agent as a Design Engine

https://github.com/nexu-io/open-design
121•steveharing1•5h ago•71 comments

Flue is a TypeScript framework for building the next generation of agents

https://flueframework.com/
3•momentmaker•43m ago•0 comments

Dotcl: Common Lisp Implementation on .NET

https://github.com/dotcl/dotcl
121•reikonomusha•2d ago•22 comments

America's Expanding Domestic Surveillance

https://www.wsj.com/articles/americas-expanding-domestic-surveillance-08b73187
100•Brajeshwar•3h ago•51 comments

Ti-84 Evo

https://education.ti.com/en/products/calculators/graphing-calculators/ti-84-evo
540•thatxliner•22h ago•441 comments

Zugzwang

https://en.wikipedia.org/wiki/Zugzwang
61•Qem•2h ago•31 comments

Show HN: Pollen – distributed WASM runtime, no control plane, single binary

https://github.com/sambigeara/pollen
75•sambigeara•2d ago•36 comments

Also-RANS: Asymmetric Numeral Systems for Entropy Coding

https://fergusfinn.com/blog/understanding-rans/
3•mezark•2d ago•0 comments

Show HN: DAC – open-source dashboard as code tool for agents and humans

https://github.com/bruin-data/dac
78•karakanb•3d ago•22 comments

Artemis II Photo Timeline

https://artemistimeline.com/#artemis-ii-walkout-nhq202604010003
306•geerlingguy•2d ago•25 comments

New research suggests people can communicate and practice skills while dreaming

https://www.newyorker.com/culture/annals-of-inquiry/its-possible-to-learn-in-our-sleep-should-we
418•XzetaU8•1d ago•244 comments

Craig Venter of Human Genome Project Dies at 79

https://www.economist.com/obituary/2026/05/01/craig-venter-raced-to-decode-the-human-genome
51•bookofjoe•6h ago•10 comments

DeepSeek V4–almost on the frontier, a fraction of the price

https://simonwillison.net/2026/Apr/24/deepseek-v4/
383•indigodaddy•1d ago•247 comments

Show HN: Mljar Studio – local AI data analyst that saves analysis as notebooks

https://mljar.com/
53•pplonski86•7h ago•10 comments

To Restore an Island Paradise, Add Fungi

https://e360.yale.edu/digest/atoll-islands-sea-level-rise-fungi
118•Brajeshwar•3d ago•32 comments

Show HN: Browser-based light pollution simulator using real photometric data

https://iesna.eu/?wasm=skyglow_demo
34•holg•9h ago•11 comments

CollectWise (YC F24) Is Hiring

https://www.ycombinator.com/companies/collectwise/jobs/rEWfZ6R-senior-forward-deployed-engineer
1•OBrien_1107•13h ago

Show HN: Filling PDF forms with AI using client-side tool calling

https://copilot.simplepdf.com/?share=a7d00ad073c75a75d493228e6ff7b11eb3f2d945b6175913e87898ec96ca...
44•nip•9h ago•22 comments