frontpage.
newsnewestaskshowjobs

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

LLMs reward expertise

https://www.seangoedecke.com/llms-reward-expertise/
394•MaxMussio•4h ago•181 comments

Ten advances in mathematics and theoretical computer science

https://openai.com/index/ten-advances-in-mathematics/
418•milkshakes•8h ago•698 comments

Ask HN: Who is hiring? (August 2026)

93•whoishiring•10h ago•98 comments

Devtools must be open source

https://blog.exe.dev/devtools-must-be-open-source
494•bryanmikaelian•11h ago•177 comments

Windows XP 2002 for the Itanium: Unbridled rage

https://virtuallyfun.com/2026/08/03/windows-xp-2002-for-the-itanium-unbridled-rage/
47•jandeboevrie•3h ago•18 comments

Amazonian civilization had estimated 3M people in 3% of forest area

https://www.science.org/content/article/odd-shapes-hidden-dense-amazon-rainforest-reveal-sprawlin...
8•marojejian•5d ago•3 comments

Ask HN: Who wants to be hired? (August 2026)

46•whoishiring•10h ago•169 comments

Smaller, faster, safer: running Kimi and GLM at scale

https://blog.cloudflare.com/smaller-faster-safer-models/
140•ascorbic•8h ago•38 comments

MiniMax H3 Day-0 Support in ComfyUI: Open Weights, Native Audio, and 2K Video

https://blog.comfy.org/p/minimax-h3-day-0-support-in-comfyui
249•vblanco•11h ago•79 comments

Celebrating 45 Years of Kermit with the First New C-Kermit Release in 15 Years

https://changelog.complete.org/archives/44456-celebrating-45-years-of-kermit-with-the-first-new-c...
122•roryirvine•8h ago•35 comments

Prevent cognitive debt by manually retyping LLM-generated code

https://ankursethi.com/blog/prevent-cognitive-debt-by-manually-retyping-llm-generated-code/
379•mpweiher•15h ago•319 comments

200 Milliseconds

https://200ms.thenodebook.com
183•dimitarpanov•2d ago•58 comments

Andy Pavlo joins ClickHouse to establish ClickHouse Labs

https://clickhouse.com/blog/andy-pavlo-joins-clickhouse
269•nikolay_sivko•11h ago•56 comments

Replacing the Kobo Libra H2O Battery

https://ei3lh.eu/2025/11/20/replacing-the-kobo-libra-h2o-battery/
44•austinallegro•4d ago•12 comments

Launch HN: Hoplite (YC S26) – Effortlessly deploy cloud coding agents

https://hoplite.sh
57•BenceRed•8h ago•50 comments

Frame selection is the whole game: notes on making LLMs watch video

https://leoaido.com/how-llms-watch-video/
7•cortexosmain•11h ago•0 comments

ZX Spectrum System Tour: Text Mode

https://bumbershootsoft.wordpress.com/2026/05/30/zx-spectrum-system-tour-text-mode/
16•rbanffy•3h ago•0 comments

How Hollywood stopped making movies in Hollywood

https://www.statsignificant.com/p/how-hollywood-stopped-making-movies
164•speckx•6d ago•189 comments

The Dunning-Kruger effect may just be a data artefact (2020)

https://www.mcgill.ca/oss/article/critical-thinking/dunning-kruger-effect-probably-not-real
118•audreyfei•5h ago•123 comments

Bonsai: Janestreet's UI Library

https://github.com/janestreet/bonsai
299•KolmogorovComp•16h ago•125 comments

AirLLM 70B inference with single 4GB GPU

https://github.com/lyogavin/airllm
185•Anon84•14h ago•75 comments

Decades-old fish sauce at abandoned factory in Canada finally being removed

https://defector.com/abandoned-fish-sauce-canada-interview
194•ohjeez•3d ago•207 comments

They Forgot What Happened Last Time: Hacking the Windows 365 Link [video]

https://media.ccc.de/v/emf2026-93-1-they-forgot-what-happened-last-time
8•Jimmc414•3d ago•0 comments

KisakCOD – open-source reimplementation of Call of Duty 4 Multiplayer

https://github.com/SwagSoftware/KisakCOD
35•skibz•6h ago•3 comments

Twenty Years of Pandoc

https://pandoc.org/twenty-years-of-pandoc.html
101•fiddlosopher•10h ago•13 comments

Massively Parallel Postgres Backups

https://planetscale.com/blog/massively-parallel-postgres-backups
85•ksec•3d ago•11 comments

Kelly Criterion Simulator

https://kellysimulator.com/
55•aleyan•3d ago•25 comments

Battle of the Beams

https://en.wikipedia.org/wiki/Battle_of_the_Beams
28•petethomas•2d ago•7 comments

The Billable Usage API: programmatic cost visibility for Cloudflare

https://blog.cloudflare.com/billable-usage-api/
43•ashleypeacock•7h ago•7 comments

What's the largest software project AI can complete on its own?

https://epoch.ai/MirrorCode
66•yusufozkan•9h ago•73 comments