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

Comments

Neywiny•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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•8mo 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: Swiftward – on-prem policy engine for LLM guardrails and UGC moderation

https://github.com/disciplinedware/swiftward
1•joker3d•27s ago•0 comments

Mysterious YouTube video that's '140 years long' has everyone confused

https://www.dexerto.com/youtube/mysterious-youtube-video-thats-140-years-long-has-everyone-confus...
1•croes•1m ago•0 comments

The New Compiler Stack: A Survey on the Synergy of LLMs and Compilers

https://hgpu.org/?p=30502
1•mpweiher•1m ago•0 comments

Proton Lumo 1.3: Introducing Projects, a better way to organize and create

https://proton.me/blog/lumo-1-3
2•teekert•2m ago•0 comments

Intent Realization Fidelity: Verifying That Systems Do What They Claim

https://zenodo.org/records/18166827
1•takko_the_boss•4m ago•0 comments

Signal creator Moxie Marlinspike wants to do for AI what he did for messaging

https://arstechnica.com/security/2026/01/signal-creator-moxie-marlinspike-wants-to-do-for-ai-what...
2•fleahunter•5m ago•0 comments

CP/M-86's delay handed Microsoft the keys to the kingdom

https://www.theregister.com/2026/01/12/why_cpm86_was_late/
2•rbanffy•6m ago•0 comments

Show HN: Img2img.net – Effortless AI Image Style Transfer Online

https://img-2-img.net
2•bozhou•8m ago•0 comments

Code Is Cheap. Coherence Is the New Bottleneck

2•moshael•9m ago•1 comments

KristelTech/Doomscrolling_Blocker A program that detects when on your phone

https://github.com/kristelTech/Doomscrolling_Blocker
2•rbanffy•9m ago•0 comments

The oceans just keep getting hotter

https://arstechnica.com/science/2026/01/the-oceans-just-keep-getting-hotter/
1•hakkikonu•10m ago•0 comments

Show HN: Xweather Live – real-time global weather maps rendered with WebGL

https://live.xweather.com/
1•unstyledcontent•12m ago•0 comments

Diffray – Open-source multi-agent code review CLI

https://github.com/diffray/diffray
1•i_strelov•15m ago•1 comments

Three LLMs in a Trenchcoat

https://buildsharerepeat.substack.com/p/three-llms-in-a-trenchcoat
2•benmann•16m ago•1 comments

The collapse of "Human Signal" on the web

https://agoranet.substack.com/p/the-collapse-of-human-signal
2•kisamoto•16m ago•2 comments

Show HN: Native app to scaffold and build Cursor-ready Next.js projects

https://vibecodingstarterkit.io
1•dpitkevics•17m ago•1 comments

Show HN: Aurora – open-source cross-platform music player (lossless)

https://github.com/bbbneo333/aurora/releases/tag/v1.0.0
1•bbbneo333•17m ago•0 comments

Making AI helpful for everyone, including the planet

https://sustainability.google
1•frizlab•17m ago•0 comments

Show HN: RAGGuard – Permission-aware retrieval for RAG applications

2•maximus242•17m ago•0 comments

Ask HN: Browser Use, Skyvern or Other for Automating Directory Submission

1•onescales•22m ago•0 comments

Leaving the Matrix

https://raccoonland.us/posts/leaving-the-matrix/
2•edent•23m ago•0 comments

Show HN: Haraltd – A cross-platform Bluetooth daemon with a JSON-based RPC

https://github.com/bluetuith-org/haraltd
3•darkhz•25m ago•0 comments

Show HN: Talkolia – An AI chatbot that understands your website

https://www.talkolia.co/
1•kokau•25m ago•0 comments

The J Incunabulum

https://tony-zorman.com/posts/j-incunabulum.html
1•fanf2•26m ago•0 comments

Ask HN: How do you use AI tools when learning unfamiliar code?

1•Rperry2174•27m ago•1 comments

The UK is shaping a future of Precrime and dissent management

https://freedomnews.org.uk/2025/04/11/how-the-uk-is-shaping-a-future-of-precrime-and-dissent-mana...
3•robtherobber•29m ago•0 comments

Fundamental skills and knowledge you must have in 2026 for SWE

https://www.youtube.com/watch?v=Jr2auYrBDA4
1•ghuntley•32m ago•0 comments

The novelists who predicted our present

https://www.theguardian.com/books/2026/jan/10/mass-surveillance-the-metaverse-making-america-grea...
2•bookofjoe•32m ago•0 comments

Same-sex sexual behavior observed in dozens of primate species

https://www.nbcnews.com/science/science-news/primates-same-sex-sexual-behavior-evolution-rcna252693
2•jackmalpo•32m ago•0 comments

What is <input type="text">?

https://twitter.com/wycats/status/1376984460088934400
1•TheAceOfHearts•34m ago•0 comments