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.

You Could Have Come Up with Kimi Delta Attention

https://blog.doubleword.ai/you-could-have-come-up-with-kimi-delta-attention
144•AnhTho_FR•1h ago•40 comments

Substack writers, you need a website

https://elizabethtai.com/2026/06/10/substack-writers-you-need-a-website/
49•speckx•53m ago•41 comments

Delayed Gratification – Proud to Be 'Last to Breaking News'

https://www.slow-journalism.com/
74•speerer•2h ago•39 comments

Discovering Cryptographic Weaknesses with Claude

https://www.anthropic.com/research/discovering-cryptographic-weaknesses
27•gslin•29m ago•1 comments

Zig's Incremental Compilation Internals

https://mlugg.co.uk/posts/incremental-compilation-internals/
78•garyhtou•2h ago•30 comments

How Do I Profile eBPF Code?

https://naveensrinivasan.com/posts/2026-07-22-how-do-i-profile-ebpf-code/
55•snaveen•1h ago•5 comments

Steel Bank Common Lisp version 2.6.7

https://sbcl.org/all-news.html?2.6.7
18•tmtvl•40m ago•1 comments

7.1 Earthquake in Japan

https://www.data.jma.go.jp/multi/quake/quake_detail.html?eventID=20260728163528&lang=en
710•krembo•10h ago•180 comments

Kimi K3 Architecture Overview and Notes

https://sebastianraschka.com/blog/2026/kimi-k3-architecture-notes.html
68•ModelForge•2h ago•7 comments

Show HN: XY – A Fast, composable, GPU-accelerated interactive plotting library

https://github.com/reflex-dev/xy
49•apetuskey•1h ago•19 comments

Harmony Explained: Progress Towards a Scientific Theory of Music (2012)

https://arxiv.org/abs/1202.4212
52•surprisetalk•2h ago•42 comments

New HIV vaccine shows unprecedented success in preclinical study

https://www.lji.org/news-events/news/post/new-hiv-vaccine-shows-unprecedented-success-in-preclini...
362•codebyaditya•4h ago•174 comments

WOFF 1.0: a milestone on W3C's journey of fonts on the web

https://www.w3.org/blog/2026/woff-1-0-a-milestone-on-w3cs-journey-of-fonts-on-the-web/
12•hn_acker•46m ago•0 comments

Scientific computing in the age of agentic AI

https://openai.com/index/scientific-computing-agentic-ai/
11•mfiguiere•38m ago•1 comments

Kimi Linear: An Expressive, Efficient Attention Architecture

https://arxiv.org/abs/2510.26692
207•ronfriedhaber•6h ago•77 comments

Now Is the Time to Give LLMs Access to the ACM Digital Library

https://cacm.acm.org/opinion/now-is-the-time-to-give-llms-access-to-the-acm-digital-library/
32•rbanffy•2h ago•12 comments

Anthropeum

https://anthropeum.com/
50•bookofjoe•2h ago•11 comments

DMARC Has Been Public Since 2012. 68.4% of Domains Still Don't Enforce It

https://ciphercue.com/blog/dmarc-enforcement-gap-rua-fragmentation-2026
117•adulion•7h ago•84 comments

How to Survive Boiling Water

https://taxa.substack.com/p/how-to-survive-boiling-water
329•cainxinth•4d ago•64 comments

So, you want to make a game engine (2023)

https://lisyarus.github.io/blog/posts/so-you-want-to-make-a-game-engine.html#part-3
21•kugurerdem•2h ago•17 comments

Using a Gaming PC's RTX 5070 from a separate Linux workstation

https://stephenkrings.com/posts/rtx-5070-linux-gpu-server/
6•microbial•5d ago•0 comments

Xenharmlib (music theory library) adds support for Just Intonation

https://xenharmlib.readthedocs.io/en/latest/whats_new_0_4_0.html
9•retooth•1h ago•0 comments

Show HN: Flashpaper – Self-destructing secret sharing with no database

https://flashpaper.app/
14•minpym•2h ago•2 comments

Show HN: Formally verified 3D CSG: Trust 93 lines spec, not 1000 lines AI code

https://github.com/schildep/verified-3d-mesh-intersection
89•permute•4h ago•39 comments

Una Watch: Garmin watch competitor but repairable, open ecosystem and USB-C

https://unawatch.com/
29•pimterry•3h ago•16 comments

Stop Killing the Internet: No Digital ID and No Age Verification

https://citizens-initiative.europa.eu/initiatives/details/2026/000011_en
132•doener•2h ago•44 comments

Google's Beyond Zero: Enterprise Security for the AI Era

https://spawn-queue.acm.org/doi/10.1145/3819083
111•jordigg•7h ago•62 comments

VMs can't boot with Network Mode set to Bridged on Apple M5 Pro machines

https://github.com/utmapp/UTM/issues/7658
42•IndySun•4h ago•23 comments

Solving Fermat: Andrew Wiles

https://www.pbs.org/wgbh/nova/proof/wiles.html
51•1970-01-01•21h ago•21 comments

Show HN: Scala Tutorials – interactive Scala 3 lessons in the browser

https://scalatutorials.com
68•eranation•3d ago•26 comments