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

Comments

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

The workers behind Meta's smart glasses can see everything

https://www.svd.se/a/K8nrV4/metas-ai-smart-glasses-and-data-privacy-concerns-workers-say-we-see-e...
479•sandbach•3h ago•256 comments

Seed of Might Color Correction Process (2023) [pdf]

https://andrewvanner.github.io/som/SoM_CC_Process_Day.pdf
62•haunter•2h ago•15 comments

Closure of the Weatheradio Service in Canada

https://www.rac.ca/rac-responds-to-the-closure-of-the-weatherradio-service-in-canada/
51•da768•2h ago•26 comments

Welcome (back) to Macintosh

https://take.surf/2026/03/01/welcome-back-to-macintosh
242•Udo_Schmitz•4h ago•153 comments

Show HN: I built a sub-500ms latency voice agent from scratch

https://www.ntik.me/posts/voice-agent
150•nicktikhonov•4h ago•41 comments

Show HN: PHP 8 disable_functions bypass PoC

https://github.com/m0x41nos/TimeAfterFree
6•m0x41nos•29m ago•0 comments

How to Build Your Own Quantum Computer

https://physics.aps.org/articles/v19/24
18•tzury•2h ago•1 comments

British Columbia to end time changes, adopt year-round daylight time

https://www.cbc.ca/news/canada/british-columbia/b-c-adopting-year-round-daylight-time-9.7111657
411•ireflect•5h ago•237 comments

First in-utero stem cell therapy for fetal spina bifida repair is safe: study

https://health.ucdavis.edu/news/headlines/first-ever-in-utero-stem-cell-therapy-for-fetal-spina-b...
246•gmays•10h ago•48 comments

New iPad Air, powered by M4

https://www.apple.com/newsroom/2026/03/apple-introduces-the-new-ipad-air-powered-by-m4/
317•Garbage•11h ago•517 comments

The 185-Microsecond Type Hint

https://blog.sturdystatistics.com/posts/type_hint/
40•kianN•3h ago•2 comments

Show HN: Govbase – Follow a bill from source text to news bias to social posts

https://govbase.com
153•foxfoxx•8h ago•69 comments

RCade: Building a Community Arcade Cabinet

https://www.frankchiarulli.com/blog/building-the-rcade/
38•evakhoury•4d ago•3 comments

Against Query Based Compilers

https://matklad.github.io/2026/02/25/against-query-based-compilers.html
14•surprisetalk•1d ago•2 comments

Show HN: Visual Lambda Calculus – a thesis project (2008) revived for the web

https://github.com/bntre/visual-lambda
16•bntr•2d ago•4 comments

Programmable Cryptography

https://0xparc.org/writings/programmable-cryptography-1
40•fi-le•2d ago•22 comments

Motorola announces a partnership with GrapheneOS

https://motorolanews.com/motorola-three-new-b2b-solutions-at-mwc-2026/
2058•km•18h ago•734 comments

Ask HN: Who is hiring? (March 2026)

165•whoishiring•9h ago•216 comments

"That Shape Had None" – A Horror of Substrate Independence (Short Fiction)

https://starlightconvenience.net/#that-shape-had-none
79•casmalia•6h ago•14 comments

Show HN: Pianoterm – Run shell commands from your Piano. A Linux CLI tool

https://github.com/vustagc/pianoterm
38•vustagc•4h ago•15 comments

Inside the M4 Apple Neural Engine, Part 1: Reverse Engineering

https://maderix.substack.com/p/inside-the-m4-apple-neural-engine
270•zdw•1d ago•69 comments

Launch HN: OctaPulse (YC W26) – Robotics and computer vision for fish farming

64•rohxnsxngh•9h ago•30 comments

Reflex (YC W23) Is Hiring Software Engineers – Python

https://www.ycombinator.com/companies/reflex/jobs
1•apetuskey•8h ago

iPhone 17e

https://www.apple.com/newsroom/2026/03/apple-introduces-iphone-17e/
192•meetpateltech•11h ago•236 comments

LFortran compiles fpm

https://lfortran.org/blog/2026/02/lfortran-compiles-fpm/
46•wtlin•3d ago•21 comments

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

66•whoishiring•9h ago•177 comments

Show HN: uBlock filter list to blur all Instagram Reels

https://gist.github.com/shraiwi/009c652da6ce8c99a6e1e0c86fe66886
98•shraiwi•5h ago•25 comments

Parallel coding agents with tmux and Markdown specs

https://schipper.ai/posts/parallel-coding-agents/
119•schipperai•11h ago•89 comments

Build your own Command Line with ANSI escape codes (2016)

https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html
35•vinhnx•2d ago•12 comments

Packaging a Gleam app into a single executable (2025)

https://www.dhzdhd.dev/blog/gleam-executable
83•todsacerdoti•9h ago•7 comments