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

ICE detains five-year-old Minnesota boy arriving home, say school officials

https://www.theguardian.com/us-news/2026/jan/21/ice-arrests-five-year-old-boy-minnesota
1•0x54MUR41•50s ago•0 comments

Seeking Co-Founder for Declarative Application Editor

1•mwhite•5m ago•0 comments

Authorization Before Retrieval: Making RAG Safe by Construction

https://www.windley.com/archives/2026/01/authorization_before_retrieval_making_rag_safe_by_constr...
1•mooreds•13m ago•0 comments

Week 1: EE 292P Atoms, Bits, and the National Interest

https://hnvr.medium.com/week-1-ee-292p-atoms-bits-and-the-national-interest-the-technology-enviro...
1•malchow•14m ago•0 comments

Why doing a mix of exercise could be the key to longer life

https://www.bbc.com/news/articles/cn0y9pqe2zro
2•kareemm•15m ago•0 comments

Monitor Cron Jobs Without Migration – DeadManPing

https://www.deadmanping.com/blog/monitor-cron-jobs
1•BlackPearl02•17m ago•0 comments

Starting a Startup at 25, 35, or 45 Is Not the Same Decision

4•alx_sukhanov•27m ago•1 comments

We spent 5 YEARS building New York City in Minecraft [video]

https://www.youtube.com/watch?v=ZouSJWXFBPk
1•KolmogorovComp•27m ago•0 comments

Rent-Only Copyright Culture Makes Us All Worse Off

https://www.eff.org/deeplinks/2026/01/rent-only-copyright-culture-makes-us-all-worse
5•hn_acker•27m ago•0 comments

Show HN: Memcachex, a high-performance Memcached client for Go

https://github.com/atsegelnyk/memcachex
1•atsegelnyk•28m ago•1 comments

Utah Continues to Ban More Books, Even as It Racks Up More Lawsuits

https://www.techdirt.com/2026/01/22/utah-continues-to-ban-more-books-even-as-it-racks-up-more-law...
3•hn_acker•28m ago•0 comments

Kona: Energy-Based Models (EBMs) for AI Reasoning

https://logicalintelligence.com/kona-ebms-energy-based-models
2•gfortaine•30m ago•0 comments

Revealjs-skill: a better way for Claude to make presentations

https://github.com/ryanbbrown/revealjs-skill
1•ryanbbrown•32m ago•0 comments

Stunnel

https://www.stunnel.org/
2•firesteelrain•33m ago•0 comments

Vibe a Guitar Pedal

https://polyend.com/endless/
4•mulhoon•34m ago•1 comments

Four Ingredients for Successful Retrofitting

https://bmin.ai/retrofitting/
1•nl•35m ago•0 comments

TikTok Strikes Deal for New U.S. Entity, Ending Long Legal Saga

https://www.nytimes.com/2026/01/22/technology/tiktok-deal-oracle-bytedance-china-us.html
5•jbegley•40m ago•0 comments

Why medieval city-builder video games are historically inaccurate (2020)

https://www.leidenmedievalistsblog.nl/articles/why-medieval-city-builder-video-games-are-historic...
25•benbreen•40m ago•5 comments

WAForth: Forth Interpreter+Compiler for WebAssembly

https://github.com/remko/waforth
1•publicdebates•43m ago•0 comments

Clean Web UI for Steve Yegge's Beads

https://github.com/nmelo/bdui
1•nmelo•43m ago•0 comments

Apple's John Ternus Takes over Design in Latest CEO Succession Move – MacRumors

https://www.macrumors.com/2026/01/22/john-ternus-apple-design-lead/
1•latexr•44m ago•0 comments

Guiding the Future of Chainguard OS: Announcing the FUD Committee

https://www.chainguard.dev/unchained/guiding-the-future-of-chainguard-os-announcing-the-fud-commi...
1•milkglass•45m ago•0 comments

Back to Bellevue

https://theamericanscholar.org/back-to-bellevue/
1•prismatic•45m ago•0 comments

Arkansas inmates restricted from receiving physical books, other media directly

https://arkansasadvocate.com/2025/12/19/arkansas-inmates-restricted-from-receiving-physical-books...
2•hn_acker•46m ago•2 comments

The Physicians of Decay

https://tantaman.substack.com/p/the-physicians-of-decay
1•tantaman•46m ago•0 comments

Yabai: A tiling window manager for macOS based on binary space partitioning

https://github.com/asmvik/yabai
2•behnamoh•46m ago•0 comments

Metastable Failures and Interactions Between Systems

https://charap.co/on-metastable-failures-and-interactions-between-systems/
3•PaulHoule•47m ago•0 comments

Node.js: New HackerOne Signal Requirement for Vulnerability Reports

https://nodejs.org/en/blog/announcements/hackerone-signal-requirement
2•latexr•48m ago•0 comments

Ispc: Origins (Part 1)

https://pharr.org/matt/blog/2018/04/18/ispc-origins
1•luu•49m ago•0 comments

Penis Size, height, and body shape influence assessment of male attractiveness

https://journals.plos.org/plosbiology/article?id=10.1371/journal.pbio.3003595
4•doener•50m ago•1 comments