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

Comments

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

Phishing Email

1•nicp•31s ago•0 comments

Productivity Is the New Data Breach

https://www.youtube.com/watch?v=e1ZM3dSfB70
1•frag•3m ago•0 comments

RalphMAD – Autonomous SDLC Workflows for Claude Code (BMAD and Ralph Loop)

1•hieutrtr•4m ago•0 comments

LibreOffice Online dragged out of the attic

https://www.theregister.com/2026/03/02/libreoffice_online_deatticized/
1•rbanffy•4m ago•0 comments

Lollygagging

https://www.merriam-webster.com/dictionary/lollygag
1•bramjoosten•7m ago•0 comments

Show HN: I Built a TypeScript ORM for DynamoDB

https://www.zeroinbox.ai/dynamodb
1•shayan-arman•7m ago•0 comments

Zed Overhauled Their ToS and Privacy Policy

https://zed.dev/blog/terms-update
1•thomascountz•7m ago•0 comments

Show HN: Spec-shaker – "Chaos engineering" for tests via semantic mutation

https://github.com/lydiazbaziny/spec-shaker
1•lydiazbaziny•9m ago•0 comments

AWS outage due to drone attacks in UAE

https://www.bbc.com/news/articles/cgk28nj0lrjo
1•stellastah•9m ago•0 comments

Greeks (Finance)

https://en.wikipedia.org/wiki/Greeks_(finance)
1•tosh•10m ago•0 comments

Show HN: Cmdop – Check your terminal from your phone, through NAT, free forever

https://github.com/commandoperator/cmdop-sdk
1•markolofsen•11m ago•0 comments

Show HN: TrueMatch – AI agents match you on observed behavior, not profiles

https://github.com/goeldivyam/truematch
2•godivyam•13m ago•0 comments

Living Human Brain Cells Play Doom on a Cortical Labs CL1 [video]

https://www.youtube.com/watch?v=yRV8fSw6HaE
1•OccamsMirror•17m ago•0 comments

Show HN: Shipcheck – Pre-launch audit tool for SaaS founders

https://www.shipcheck.pro/
1•fiynraj•19m ago•2 comments

Deterministic and AI-agent broker import to prevent portfolio data corruption

https://www.portfolio-terminal.com/demo
1•julien_devv•19m ago•2 comments

The Future Is AC/DC: The Agent Centric Development Cycle

https://www.sonarsource.com/blog/the-future-is-ac-dc-the-agent-centric-development-cycle/
1•MoustaphaSaad•21m ago•1 comments

MyFitnessPal has acquired Cal AI, the viral calorie app built by teens

https://techcrunch.com/2026/03/02/myfitnesspal-has-acquired-cal-ai-the-viral-calorie-app-built-by...
1•svenfaw•24m ago•0 comments

Show HN: Rriftt_ai.h – A bare-metal, dependency-free C23 tensor engine

https://github.com/Rriftt/rriftt_ai.h
3•Rriftt•26m ago•0 comments

Iran war heralds era of AI-powered bombing quicker than 'speed of thought'

https://www.theguardian.com/technology/2026/mar/03/iran-war-heralds-era-of-ai-powered-bombing-qui...
2•saeedesmaili•27m ago•4 comments

Iranian cryptoasset outflows surge 700% following airstrikes

https://www.elliptic.co/blog/iranian-cryptoasset-outflows-surge-700-percent-following-attacks
1•giuliomagnifico•28m ago•0 comments

Attempting to detect smart glasses nearby and warn you

https://blog.adafruit.com/2026/03/02/attempting-to-detect-smart-glasses-nearby-and-warn-you/
1•EvgeniyZh•36m ago•0 comments

Show HN: Instbyte – Self-hosted LAN sharing tool, run with npx, no cloud

https://github.com/mohitgauniyal/instbyte
2•mohitgauniyal•36m ago•1 comments

Feynman's War: Modelling Weapons, Modelling Nature (1986) [pdf]

https://gwern.net/doc/science/physics/1998-galison.pdf
1•nill0•39m ago•0 comments

The Download: protesting AI, and what's floating in space

https://www.technologyreview.com/2026/03/02/1133811/the-download-protesting-ai-and-whats-floating...
1•joozio•42m ago•0 comments

LeRobot: An Open-Source Library for End-to-End Robot Learning

https://arxiv.org/abs/2602.22818
2•nill0•42m ago•0 comments

PDF Tools

https://www.pdffixnow.com
1•instahotstar•47m ago•0 comments

Comfy.org

https://blog.comfy.org/
1•VanessaMGSA•47m ago•0 comments

Show HN: My OpenClaw knows EXACTLY what it did a week ago. Thanks to "hmem"-MCP

1•Bumblebiber•51m ago•0 comments

Africa Imported Europe's Worst Idea

https://magatte.substack.com/p/how-africa-imported-europes-worst
3•EvgeniyZh•51m ago•0 comments

Anthropic's Feud with Pentagon Earns It Fans Amid the Blowback

https://www.wsj.com/tech/ai/anthropics-feud-with-pentagon-earns-it-fans-amid-the-blowback-f7e2bb83
2•JumpCrisscross•53m ago•0 comments