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

Replacing Google Analytics with Matomo on a Pi in a Cupboard

https://alexlance.blog/analytics.html
1•alance•1m ago•0 comments

The LLM Looked Smart. The Metrics Disagreed

https://tiago.rio.br/work/general/articles/llm-looked-smart-metrics-disagreed/
1•timotta•5m ago•0 comments

Why does Amazon have no Western rivals?

https://www.bbc.com/news/articles/cg7p5nr307mo
1•dabinat•6m ago•0 comments

3D R/Place

https://outer.one
1•mikidoodle•6m ago•0 comments

The Watch – Runway Song

https://www.youtube.com/watch?v=uF7lmsP3vJY
1•marcelix•9m ago•0 comments

188,000 Show HN posts, 14 years of data: what predicts GitHub stars

https://danfking.github.io/blog/2026/04/23/show-hn-by-the-numbers/
2•BundyBear•12m ago•0 comments

Hypen – Declarative UI Language for Cross-Platform Development

https://hypen.space/introducing-hypen
2•ravenical•23m ago•0 comments

Show HN: Cheap-IM – CPU-only voice agent approximating Thinking Machines' demo

https://github.com/kouhxp/cheap-im
1•mrkn1•27m ago•0 comments

Zero, a systems language for small native agent tools

https://github.com/vercel-labs/zero
1•mjgil•31m ago•0 comments

ZeroBloat: Open-source desktop app for removing Android bloatware

https://github.com/AdhwaithAS/ZeroBloat
2•pentagrama•33m ago•0 comments

Show HN: Building ClueDay, a daily clue-based word-game

https://tanyagupta10.substack.com/p/if-you-havent-vibecoded-already-build
1•tannyc•39m ago•0 comments

Target can't measure their own bins

https://ninjacheetah.dev/2026/05/17/target-cant-measure.html
2•argee•43m ago•0 comments

Searching "remove definition" on Google results in pointless AI text

https://www.google.com/search?q=remove+definition
2•tech234a•43m ago•0 comments

Show HN: I containerized my AI agents and dev tools

https://github.com/SamInTheShell/aetherion
1•SamInTheShell•49m ago•0 comments

I made realtime raytraced reflections for my portfolio site

https://taggartmaher.com/projects/this-website
2•xialo•50m ago•0 comments

Show HN: Agetor - An open-source Harness Orchestrator

https://github.com/alamops/agetor
1•drakochack•51m ago•0 comments

Do LLMs hold the opinions they give you?

https://twitter.com/pandya_marut/status/2056151597642838487
1•mwiki•59m ago•0 comments

Does Wellington have the most beautiful commute in the world?

https://www.rnz.co.nz/news/regions_wellington/595529/cyclists-commute-at-sunrise-on-the-beautiful...
1•colinprince•1h ago•0 comments

Do less so you can do better (2020)

https://www.indiehackers.com/post/do-less-so-you-can-do-it-better-3ea77e92b4
2•chr15m•1h ago•0 comments

WriteUp: 16 Bytes of x86 that turn Matrix rain into sound

https://hellmood.111mb.de//wake_up_16b_writeup.html
3•HellMood•1h ago•0 comments

Scientists have invented a way to erase bad memories. But should we?

https://www.sciencefocus.com/future-technology/erase-painful-memories
4•amichail•1h ago•2 comments

Rust Async and the Arm Generic Timer

https://thejpster.org.uk/blog/blog-2026-05-17/
1•hasheddan•1h ago•0 comments

Dealing with a Fake a World

2•morpheos137•1h ago•1 comments

Design posters showcasing your country's electrical grid

https://github.com/open-energy-transition/grid2poster
14•lyoncy•1h ago•1 comments

100% Vibe Code

https://humansvsai.io
1•creatorcuffee•1h ago•0 comments

Why ML is a metaphor for life

https://adeshpande3.github.io/Why-Machine-Learning-is-a-Metaphor-For-Life
2•_josh_meyer_•1h ago•0 comments

Finding the Time on AArch32

https://thejpster.org.uk/blog/blog-2026-05-16/
1•hasheddan•1h ago•0 comments

Meta AI Incognito Mode Chats

https://about.fb.com/news/2026/05/incognito-chat-whatsapp-meta-ai/
1•hdjY28•1h ago•0 comments

Financial Services Hackathon for Autism

https://fsi-hack4autism.github.io
1•hbcondo714•1h ago•0 comments

I reduced my OpenClaw token usage by 10x

https://brtkwr.com/posts/2026-05-17-reducing-openclaw-token-usage/
1•brtkwr•1h ago•0 comments