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

Show HN: Thisorthis.ai – Compare responses from 50 AI models side-by-side

https://thisorthis.ai/ai-playground
1•parthsamin•26s ago•0 comments

'Starkiller' Phishing Service Proxies Real Login Pages, MFA

https://krebsonsecurity.com/2026/02/starkiller-phishing-service-proxies-real-login-pages-mfa/
1•Bender•1m ago•0 comments

Show HN: Anno – API that cuts AI web-scraping token costs by 90%

https://www.evolvingintelligence.ai/anno
1•evo-dragon•2m ago•0 comments

Show HN: System prompts and models of top AI tools (Claude Code, Cursor, Devin)

https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools
1•CodeBit26•4m ago•0 comments

Show HN: Clawphone – Twilio voice/SMS gateway for AI agents using TwiML polling

https://github.com/ranacseruet/clawphone
1•ranacseruet•4m ago•0 comments

Automatically Learning Skills for Coding Agents

https://gepa-ai.github.io/gepa/blog/2026/02/18/automatically-learning-skills-for-coding-agents/
1•xdotli•6m ago•0 comments

Interns with Chainsaws

https://anhvietle.substack.com/p/interns-with-chainsaws
1•haizzz•7m ago•0 comments

Get to Know OpenClaw Security

https://get-to-know-openclaw-security-model.vercel.app/
1•ramoz•7m ago•0 comments

Why Don't We Treat AI Like We Treated Wikipedia?

https://medium.com/@mycahp/why-dont-we-treat-ai-like-we-treated-wikipedia-07ece535dd09
1•hacym•8m ago•0 comments

We Reached 74.8% on terminal-bench with Terminus-KIRA

https://krafton-ai.github.io/blog/terminus_kira_en/
1•xdotli•10m ago•0 comments

Product Design Is Changing

https://rogerwong.me/2026/02/product-design-is-changing/
1•rogerwong•13m ago•1 comments

Most AI Startups Are Just API Wrappers – We Measured the Economics

https://no-edit.lovable.app/
1•epic_ai•15m ago•1 comments

Toms BackGround Remover

https://tomdahne.com/TomsBGRemover/index.html
1•ezimedia•18m ago•0 comments

Thunderstorms conjure coronae in treetops, observed outdoors for the first time

https://news.agu.org/press-release/thunderstorms-conjure-ghostly-coronae-in-treetops-observed-out...
1•geox•20m ago•0 comments

Ask HN: How do you handle API rate limits in production?

1•rjpruitt16•23m ago•1 comments

Getting Real with LLMs

https://www.giladpeleg.com/blog/getting-real-with-llms
1•fagnerbrack•24m ago•0 comments

Show HN: Scamometer – AI scam score for any suspicious message

https://scamometer.io
2•crawde•24m ago•0 comments

NIST Seeking Public Comment on AI Agent Security (Deadline: March 9, 2026)

https://www.federalregister.gov/documents/2026/01/08/2026-00206/request-for-information-regarding...
6•ascarola•27m ago•2 comments

Port of San Francisco's dilapidated, derelict drydocks

https://missionlocal.org/2026/02/port-of-san-francisco-dry-dock-pier-68-70/
2•kaycebasques•29m ago•0 comments

The Bash Primer

http://www.compciv.org/bash-guide/
3•bobjordan•31m ago•1 comments

Solving Impossible Problems for Fun and Profit – Dan Gelbart [video]

https://www.youtube.com/watch?v=UTgrWmOk4q8
1•YZF•31m ago•0 comments

White House names new pick for Nevada federal prosecutor

https://www.nevadaappeal.com/news/2026/feb/18/white-house-names-new-pick-for-nevada-federal-prose...
2•qualudeheart•32m ago•0 comments

Show HN: Dance of Tal – Decompose, mix, and reuse AI rules with an MCP server

https://github.com/monarchjuno/dance-of-tal
1•monarchjuno•38m ago•0 comments

Show HN: 32M lines of AI code – GED to AGI

https://github.com/lordwilsonDev/GITHUB_AI_PROJECTS_PACKAGE
1•lordwilsonDev•40m ago•0 comments

The Pope Bot – OpenClaw Alternative

https://github.com/stephengpope/thepopebot
1•peter_d_sherman•45m ago•0 comments

Scheme: An Interpreter for Extended Lambda Calculus

https://research.scheme.org/lambda-papers/lambda-papers-scheme-report.html
2•so-cal-schemer•47m ago•1 comments

Iowa Farmers Are Leading the Fight for Repair

https://www.ifixit.com/News/115722/iowa-farmers-are-leading-the-fight-for-repair
3•gnabgib•48m ago•0 comments

The Lambda Papers

https://research.scheme.org/lambda-papers/
2•so-cal-schemer•49m ago•1 comments

Show HN: A deadly simple tmux windows like start UI

https://github.com/liyu1981/tmux_start_ui
2•liyu1981au•1h ago•1 comments

Landslides kill 227 at Democratic Republic of Congo coltan mines

https://www.wsws.org/en/articles/2026/02/09/jndz-f09.html
2•PaulHoule•1h ago•1 comments