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

Comments

Neywiny•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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";
  }

What is jj and why should I care?

https://steveklabnik.github.io/jujutsu-tutorial/introduction/what-is-jj-and-why-should-i-care.html
164•tigerlily•3h ago•86 comments

DaVinci Resolve – Photo

https://www.blackmagicdesign.com/products/davinciresolve/photo
754•thebiblelover7•11h ago•200 comments

NimConf 2026: Dates Announced, Registrations Open

https://nim-lang.org/blog/2026/04/07/nimconf-2026.html
46•moigagoo•2h ago•9 comments

Backblaze has stopped backing up your data

https://rareese.com/posts/backblaze/
403•rrreese•5h ago•249 comments

A new spam policy for “back button hijacking”

https://developers.google.com/search/blog/2026/04/back-button-hijacking
530•zdw•10h ago•315 comments

Two Months After I Gave an AI $100 and No Instructions

https://www.sebastian-jais.de/blog/two-months-alma-experiment
11•gleipnircode•11m ago•4 comments

Someone bought 30 WordPress plugins and planted a backdoor in all of them

https://anchor.host/someone-bought-30-wordpress-plugins-and-planted-a-backdoor-in-all-of-them/
1047•speckx•19h ago•299 comments

Introspective Diffusion Language Models

https://introspective-diffusion.github.io/
117•zagwdt•5h ago•30 comments

GitHub Stacked PRs

https://github.github.com/gh-stack/
786•ezekg•17h ago•425 comments

The acyclic e-graph: Cranelift's mid-end optimizer

https://cfallin.org/blog/2026/04/09/aegraph/
13•tekknolagi•4d ago•1 comments

Franklin's bad ads for Apple ][ clones and the beloved impersonator they depict

https://buttondown.com/suchbadtechads/archive/franklin-ace-1000/
59•rfarley04•3d ago•30 comments

The M×N problem of tool calling and open-source models

https://www.thetypicalset.com/blog/grammar-parser-maintenance-contract
37•remilouf•4d ago•12 comments

The exponential curve behind open source backlogs

https://armanckeser.com/writing/jellyfin-flow
11•armanckeser•2h ago•2 comments

Ransomware Is Growing Three Times Faster Than the Spending Meant to Stop It

https://ciphercue.com/blog/ransomware-claims-grew-faster-than-security-spend-2025
45•adulion•4h ago•38 comments

Distributed DuckDB Instance

https://github.com/citguru/openduck
100•citguru•7h ago•21 comments

The Case Against Gameplay Loops

https://blog.joeyschutz.com/the-case-against-gameplay-loops/
13•coinfused•2h ago•6 comments

Lean proved this program correct; then I found a bug

https://kirancodes.me/posts/log-who-watches-the-watchers.html
304•bumbledraven•13h ago•142 comments

The Great Majority: Body Snatching and Burial Reform in 19th-Century Britain

https://publicdomainreview.org/essay/the-great-majority/
9•apollinaire•3d ago•1 comments

WiiFin – Jellyfin Client for Nintendo Wii

https://github.com/fabienmillet/WiiFin
197•throwawayk7h•14h ago•91 comments

Multi-Agentic Software Development Is a Distributed Systems Problem

https://kirancodes.me/posts/log-distributed-llms.html
61•tie-in•8h ago•27 comments

MOS tech 6502 8-bit microprocessor in pure SQL powered by Postgres

https://github.com/lasect/pg_6502
46•adunk•7h ago•5 comments

A soft robot has no problem moving with no motor and no gears

https://engineering.princeton.edu/news/2026/04/08/soft-robot-has-no-problem-moving-no-motor-and-n...
49•hhs•4d ago•13 comments

Nothing Ever Happens: Polymarket bot that always buys No on non-sports markets

https://github.com/sterlingcrispin/nothing-ever-happens
448•m-hodges•22h ago•243 comments

Lumina – a statically typed web-native language for JavaScript and WASM

https://github.com/nyigoro/lumina-lang
30•light_ideas•4d ago•11 comments

US appeals court declares 158-year-old home distilling ban unconstitutional

https://nypost.com/2026/04/11/us-news/us-appeals-court-declares-158-year-old-home-distilling-ban-...
415•t-3•1d ago•281 comments

Design and implementation of DuckDB internals

https://duckdb.org/library/design-and-implementation-of-duckdb-internals/
150•mpweiher•3d ago•9 comments

Write less code, be more responsible

https://blog.orhun.dev/code-responsibly/
127•orhunp_•3d ago•71 comments

Make tmux pretty and usable (2024)

https://hamvocke.com/blog/a-guide-to-customizing-your-tmux-conf/
408•speckx•22h ago•249 comments

N-Day-Bench – Can LLMs find real vulnerabilities in real codebases?

https://ndaybench.winfunc.com
86•mufeedvh•15h ago•27 comments

Rust Threads on the GPU

https://www.vectorware.com/blog/threads-on-gpu/
99•PaulHoule•4d ago•29 comments