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•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();
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.

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

The Mysterious XF86AudioPlay Issue

https://michael-prokop.at/blog/2026/05/20/the-mysterious-xf86audioplay-issue/
1•JNRowe•1m ago•0 comments

VPNs: The "Most Trusted" Security Tool Until Claude Roasts It in a Weekend

https://www.hacktron.ai/blog/cve-2026-0265-panos-globalprotect-cas-auth-bypass
1•jordybg•3m ago•0 comments

Show HN: Macfigure – Mac configuration in pkl. Simple alternative to Nix-Darwin

https://github.com/Quintisimo/macfigure
1•quintisimo•3m ago•0 comments

Ask HN: Transition from Engineering Manager to IC

1•lavsv•4m ago•0 comments

The Secrets Revealed in SpaceX's IPO Filing

https://www.wsj.com/business/spacex-ipo-takeaways-cea33689
1•1vuio0pswjnm7•5m ago•0 comments

SpaceX Filing Reveals $4.28B Loss, Musk's Tight Grip (3)

https://news.bloomberglaw.com/capital-markets/musks-spacex-files-publicly-for-nasdaq-ipo-under-sy...
2•1vuio0pswjnm7•6m ago•0 comments

SpaceX IPO filing lays bare losses and Musk control as it stakes future on AI

https://www.reuters.com/legal/transactional/bound-mars-elon-musks-spacex-unveils-filing-blockbust...
2•1vuio0pswjnm7•8m ago•0 comments

Reconnecting. – – 5/5 why don't they fix codex

1•apoorvdarshan•9m ago•0 comments

Why is writing good test cases still painfully manual in 2026?

https://calendly.com/qualityfolio2026/30min
1•Daniel_Carter•10m ago•0 comments

Lazydiff: Terminal PR Review with AST-Aware Semantic Diff Rendering

https://github.com/Ataraxy-Labs/lazydiff
1•rohanucla•14m ago•0 comments

Is Python Becoming Pinyin?

https://lernerpython.com/2026/05/19/is-python-becoming-pinyin/
1•reuven•23m ago•0 comments

Rewrite System Showdown: Stochastic Search vs. EqSat

https://arxiv.org/abs/2605.19005
1•pcfwik•27m ago•0 comments

Scheme Interpreter

https://cs61a.org/proj/scheme/
1•HiPHInch•30m ago•0 comments

Understanding KV Cache: The Hidden Memory Cost of Serving LLMs

https://melchi.me/posts/kv-cache/
1•colescodes•32m ago•0 comments

Opn-Chat

https://opn-chat-v1-freebuff.vercel.app
1•fcapuz•33m ago•0 comments

Workers in India are training robots that may replace them

https://indianexpress.com/article/business/workers-india-training-robots-replace-factory-10698712/
3•methuselah_in•33m ago•0 comments

Why does the arrow (->) operator in C exist?

https://stackoverflow.com/questions/13366083/why-does-the-arrow-operator-in-c-exist
3•gnabgib•37m ago•0 comments

Trump admin didn't want Ebola-exposed Americans, sent them to Berlin, Prague

https://arstechnica.com/health/2026/05/trump-admin-didnt-want-ebola-exposed-americans-sent-them-t...
4•donutshop•40m ago•0 comments

Housekeeping Wages to Top $110K Year in New York City by Early 2030s

https://loyaltylobby.com/2026/05/20/housekeeping-wages-to-top-110k-year-in-new-york-city-by-early...
1•lxm•43m ago•0 comments

Amazon E-Bikes Take Root in Manhattan and Brooklyn

https://www.nytimes.com/2026/05/19/business/amazon-cargo-bikes-delivery.html
1•lxm•44m ago•0 comments

Google's open source distributed agent runtime

https://github.com/google/ax
2•rnella01•47m ago•0 comments

Birth Rate Debate: 40% of Girls Will Never Be Mothers [video]

https://www.youtube.com/watch?v=8eCM3NTBeb4
2•poiuyt098•47m ago•2 comments

Why does the arrow (->) operator in C exist?

https://lobste.rs/s/garq37/why_does_arrow_operator_c_exist
2•maxloh•50m ago•1 comments

Why Fashion Needs a World Model

https://twitter.com/ArkidMitra/status/2057130009203298693
1•Arkid•52m ago•1 comments

Web5-Mesh (IAON)

https://github.com/mamanga1/Web5-Mesh/tree/main
2•mamanga•55m ago•1 comments

Show HN: SafeRun – Replay debugging and inline prevention for AI agents 3

1•Tidianez•56m ago•0 comments

25 years ago Sega figured out the internet with Phantasy Star Online

https://www.avclub.com/sega-phantasy-star-online-gaming
2•debo_•59m ago•0 comments

Show HN: Agent Chat Bridge – give AI IDE agents an async callback

https://github.com/sathvikc/agent-chat-bridge
1•sathvikchinnu•1h ago•0 comments

Xcodes: Command-line Xcode version manager

https://github.com/XcodesOrg/xcodes
1•Lwrless•1h ago•0 comments

Show HN: SnapAPI – Screenshot, metadata extraction, and PDF generation API

https://snap.michaelcli.com
1•msmolkin•1h ago•0 comments