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.

El Niño Is Wreaking Havoc on Pacific Fisheries

https://www.wired.com/story/el-nino-wreaking-havoc-on-pacific-fisheries/
1•beardyw•54s ago•0 comments

Lumvelle Drops ReviEwS (2026): We Tried It My Honest Review

https://gamma.app/embed/Lumvelle-Drops-ReviEwS-2026-We-Tried-It-My-Honest-Review-8ki1ftfh003qqdn
1•brentrq•2m ago•0 comments

Documentation is still in your Mum's filing cabinet

https://gerireid.com/blog/organising-documentation-for-humans-and-ai/
1•eigenBasis•6m ago•0 comments

Ask HN: Does your website work on Nordstjernen Web Browser?

1•roschdal•8m ago•0 comments

World Model Is the New Inflection Point

https://rajatghosh11.substack.com/p/one-model-to-rule-them-all
1•rghosh8•8m ago•0 comments

A font that humans can read but AI cannot

https://www.mixfont.com/ghost-font
1•justswim•10m ago•0 comments

Show HN: Image Generation API with QR code tracking and MCP support

https://templateson.com
1•maz225•10m ago•0 comments

Cost vs. accuracy in CursorBench 3.1: the effect of family and spend

https://www.shibaprasadb.com/2026/07/09/cursorbench-analysis.html
1•shibaprasadb•12m ago•0 comments

Show HN: A strategic word game where you make many words with 1 letter per turn

https://play.letterphile.com
1•sonOfHades•13m ago•0 comments

The Personal Safe – Zero-knowledge encrypted backup for your own S3 bucket

https://github.com/wocdamjack/thepersonalsafe
1•wocdamjack•15m ago•0 comments

Lumvelle ReviEwS (2026): We Tried It My Honest Review

https://gamma.app/embed/Lumvelle-ReviEwS-2026-We-Tried-It-My-Honest-Review-ge43hr5uq6eoxu3
1•bayszalu•17m ago•0 comments

Safari sidebar silently loads loads all your bookmarks

https://lapcatsoftware.com/articles/2026/7/1.html
2•JumpCrisscross•20m ago•0 comments

Open-source finance infrastructure in Rust

https://www.railsinfra.com
1•sibabale•29m ago•1 comments

Almost $1B Later, the US Still Can't Make a Medical Glove

https://www.bloomberg.com/news/features/2026-07-07/why-it-s-so-difficult-to-produce-100-american-...
5•helsinkiandrew•31m ago•1 comments

Consumers unsatisfied despite world-class networks

https://billbennett.co.nz/nz-telecom-customer-satisfaction-declines-comcom-report/
1•JumpCrisscross•32m ago•0 comments

New Earth Time – 360 degrees of time (2000)

https://newearthtime.net/
1•networked•32m ago•0 comments

FCC weighs changing E-Rate program, which lowers school internet bills

https://www.npr.org/2026/07/10/nx-s1-5878405/fcc-erate-schools-internet-discount
2•jonbaer•36m ago•0 comments

Microsoft latest report shows 25% emissions raised due to AI data centers

https://www.windowscentral.com/microsoft/dropping-greenwashing-credits-and-expanding-ai-datacente...
3•pjmlp•36m ago•0 comments

Ukraine's Amazon for war: Inside the marketplace built for the military

https://www.youtube.com/watch?v=BZaIh5we0bY
1•doener•37m ago•0 comments

Zeitpyramide

https://en.wikipedia.org/wiki/Zeitpyramide
3•doener•39m ago•0 comments

Kids (With Phones) Are Alright

https://heatherburns.tech/2026/07/08/the-kids-with-phones-are-alright/
1•JumpCrisscross•39m ago•0 comments

Timeline of the Far Future

https://en.wikipedia.org/wiki/Timeline_of_the_far_future
1•doener•40m ago•0 comments

Loom Document Search Engine

https://gitlab.com/swiss-armed-forces/cyber-command/cea/loom
1•ano-ther•42m ago•0 comments

In defense of not understanding your codebase

https://www.seangoedecke.com/in-defense-of-not-understanding-your-codebase/
1•suprjami•50m ago•1 comments

Show HN: ServiceBeard – Turn your support mailbox into an issue board

https://servicebeard.app/
2•hongaar•53m ago•0 comments

Adam Curtis – All Watched over by Machines of Loving Grace

https://en.wikipedia.org/wiki/All_Watched_Over_by_Machines_of_Loving_Grace_(TV_series)
4•mrauha•55m ago•1 comments

MonitorSpider. Uptime, page-change detection and login monitoring in one

https://monitorspider.com
1•hitechist•56m ago•0 comments

Show HN: Web-Performer – Run HTTP/GraphQL Requests from YAML (TypeScript CLI)

https://github.com/Techthos/web-performer
1•alex20465•59m ago•0 comments

Key Volkswagen shareholder pitches producing China car models in Germany

https://www.reuters.com/world/china/key-volkswagen-shareholder-pitches-producing-china-car-models...
2•tosh•1h ago•0 comments

Long March 10 booster cable catch, from the ship

https://twitter.com/CNSpaceflight/status/2075743529985605677
2•hunglee2•1h ago•0 comments