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

Launch HN: TeamOut (YC W22) – AI agent for planning company events

https://app.teamout.com/ai
1•vincentalbouy•1m ago•0 comments

Agent Skills for Data Engineering (Airflow, Dbt, Analytics)

https://github.com/astronomer/agents
1•tayloramurphy•2m ago•0 comments

What are the best coping mechanisms for AI Fatalism?

1•johnb95•3m ago•0 comments

All New adobaRo – an execution-focused AI for global content workflows

1•adobaro•3m ago•0 comments

Show HN: Md files as B2B AI agent sandbox – no production data needed

https://publish.obsidian.md/frogy/30+Frogy+Telegram+Beta+Program/30-21+HN+%2B+Technical+Writing/2...
1•rolodexter2023•3m ago•0 comments

Show HN: Interactive visualization of X's feed algorithm – ML in browser

https://prabal.ca/x-algorithm/
3•prabal97•3m ago•0 comments

TLDraw plans to move their tests to a closed-source repo

https://github.com/tldraw/tldraw/issues/8082
1•switz•3m ago•0 comments

Show HN: EventDock – Webhook reliability for $29/mo (vs $490 alternatives)

https://eventdock.app/
1•kidsil•5m ago•0 comments

Show HN: Velar – Local privacy firewall for AI

https://github.com/ubcent/velar
1•ubcent•5m ago•0 comments

Show HN: I cut LLM API bill by 55% with a Python text compressor, no AI involved

https://agentready.cloud/hn
1•christalingx•5m ago•1 comments

Bullshit Benchmark: how do chatbots respond to silly questions?

https://github.com/petergpt/bullshit-benchmark
1•twistorial•6m ago•0 comments

Show HN: Skill or Kill – Can you spot the malicious AI agent skill?

https://skillorkill.dev/
2•jfaganel99•6m ago•1 comments

Spanish company releases free compressed AI model

https://techcrunch.com/2026/02/24/spanish-soonicorn-multiverse-computing-releases-free-compressed...
1•mastazi•9m ago•0 comments

Gleam is straightforward, predictable and stable

https://builders.perk.com/gleam-is-boring-so-i-went-to-a-conference-about-it-8f08a52c3de3
4•crowdhailer•9m ago•0 comments

A Round Up and Comparison of 10 Open-Weight LLM Releases in Spring 2026

https://magazine.sebastianraschka.com/p/a-dream-of-spring-for-open-weight
1•MindGods•10m ago•0 comments

Show HN: Seite static site generator with MCP server and Claude Code integration

https://seite.sh/
1•sanchezomar•12m ago•0 comments

Mitochondria May Be the Key to Longevity

https://www.nytimes.com/2026/02/19/well/mitochondria-longevity-health.html
2•bookofjoe•13m ago•1 comments

Language Models will be Scaffolds

https://alexzhang13.github.io/blog/2026/scaffold/
1•vinhnx•13m ago•0 comments

Raijin – coding agent harness written in Go [MIT license]

https://github.com/francescoalemanno/raijin-mono
1•frankzig•13m ago•0 comments

Show HN: First native zeroclaw build on Android/Termux (aarch64, no proot)

1•bleaknarratives•16m ago•0 comments

Electrical control of magnetism in 2D materials promises to advance spintronics

https://phys.org/news/2026-02-electrical-magnetism-2d-materials-advance.html
1•bilsbie•16m ago•0 comments

A Curious Trig Identity

https://www.johndcook.com/blog/2026/02/24/a-curious-trig-identity/
2•ibobev•17m ago•0 comments

Trig of Inverse Trig

https://www.johndcook.com/blog/2026/02/25/trig-of-inverse-trig/
1•ibobev•17m ago•0 comments

Python Type Checker Comparison: Empty Container Inference

https://pyrefly.org/blog/container-inference-comparison/
1•ocamoss•18m ago•0 comments

Jjq, a local merge queue for jj

https://pauladamsmith.com/blog/2026/02/introducing-jjq-a-local-merge-queue-for-jj.html
1•ibobev•18m ago•0 comments

Tech legend Stewart Brand on Musk, Bezos and his extraordinary life

https://www.theguardian.com/technology/2026/feb/25/tech-legend-stewart-brand-on-musk-bezos-and-hi...
1•rwmj•19m ago•0 comments

The new Design for Stack Overflow is now live [beta]

https://beta.stackoverflow.com/
4•gortok•19m ago•2 comments

Show HN: I scanned 35 SaaS products across ChatGPT, Claude, Perplexity, Gemini

https://www.bersyn.com/
1•gissurthor•20m ago•0 comments

Illusion and Well-Being: A Perspective on Mental Health [pdf]

https://faculty.washington.edu/jdb/articles/Illusion%20and%20Well-Being.pdf
1•RickJWagner•20m ago•1 comments

UAA – A spec for AI and Human coding collaboration

1•alexandretrotel•20m ago•0 comments