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

Comments

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

Hardware Attestation as Monopoly Enabler

https://grapheneos.social/@GrapheneOS/116550899908879585
1399•ChuckMcM•14h ago•460 comments

Local AI needs to be the norm

https://unix.foo/posts/local-ai-needs-to-be-norm/
1022•cylo•14h ago•442 comments

The Greatest Shot in Television: James Burke Had One Chance to Nail This Scene (2024)

https://www.openculture.com/2024/10/the-greatest-shot-in-television.html
132•susam•5h ago•52 comments

Running local models on an M4 with 24GB memory

https://jola.dev/posts/running-local-models-on-m4
277•shintoist•8h ago•84 comments

I'm going back to writing code by hand

https://blog.k10s.dev/im-going-back-to-writing-code-by-hand/
301•dropbox_miner•6h ago•120 comments

7 lines of code, 3 minutes: Implement a programming language (2010)

https://matt.might.net/articles/implementing-a-programming-language/
40•azhenley•3h ago•10 comments

Obsidian plugin was abused to deploy a remote access trojan

https://cyber.netsecops.io/articles/obsidian-plugin-abused-in-campaign-to-deploy-phantom-pulse-rat/
186•cmbailey•10h ago•94 comments

An AI coding agent, used to write code, needs to reduce your maintenance costs

https://www.jamesshore.com/v2/blog/2026/you-need-ai-that-reduces-your-maintenance-costs
139•cratermoon•8h ago•35 comments

Incident Report: CVE-2024-YIKES

https://nesbitt.io/2026/02/03/incident-report-cve-2024-yikes.html
500•miniBill•14h ago•128 comments

Mythos Finds a Curl Vulnerability

https://daniel.haxx.se/blog/2026/05/11/mythos-finds-a-curl-vulnerability/
51•TangerineDream•1h ago•14 comments

Show HN: adamsreview – better multi-agent PR reviews for Claude Code

https://github.com/adamjgmiller/adamsreview
25•adamthegoalie•5h ago•6 comments

Ask HN: What are you working on? (May 2026)

177•david927•14h ago•637 comments

How Fast Does Claude, Acting as a User Space IP Stack, Respond to Pings?

https://dunkels.com/adam/claude-user-space-ip-stack-ping/
66•adunk•9h ago•17 comments

First tunnel element of the Fehmarnbelt Tunnel immersed

https://www.arup.com/en-us/news/first-fehmarnbelt-tunnel-element-lowered/
87•robin_reala•3d ago•22 comments

Seeing Birdsong

https://www.lucioarese.net/seeing-birdsong/
18•carabiner•3d ago•1 comments

dBase: 1979-2026

https://delphinightmares.substack.com/p/dbase-1979-2026
65•deeaceofbase•3d ago•19 comments

Guy Goma's Accidental BBC Interview Lives on After 20 Years

https://www.nytimes.com/2026/05/06/business/media/bbc-guy-goma-interview.html
104•nxobject•2d ago•22 comments

I returned to AWS and was reminded why I left

http://fourlightyears.blogspot.com/2026/05/i-returned-to-aws-and-was-reminded-hard.html
749•andrewstuart•1d ago•524 comments

Traces Of Humanity

https://tracesofhumanity.org/hello-world/
153•alex77456•14h ago•22 comments

Stop MitM on the first SSH connection, on any VPS or cloud provider

https://www.joachimschipper.nl/Stop%20MITM%20on%20the%20first%20SSH%20connection,%20on%20any%20VP...
111•JoachimSchipper•2d ago•61 comments

The people preserving the scientific practice of bird banding

https://thenarwhal.ca/bird-banding-ontario/
51•bookofjoe•3d ago•0 comments

Eight More '8-Bit Era' Microprocessors

https://thechipletter.substack.com/p/eight-more-8-bit-era-microprocessors
69•klelatti•2d ago•22 comments

The locals don't know

https://www.quarter--mile.com/The-Locals-Dont-Know
152•herbertl•15h ago•107 comments

Maryland citizens hit with $2B power grid upgrade for out-of-state AI

https://www.tomshardware.com/tech-industry/artificial-intelligence/maryland-citizens-slapped-with...
233•lemonberry•10h ago•130 comments

Ice Cream Blending (1965) [pdf]

https://bitsavers.org/pdf/ibm/generalInfo/E20-0156-0_Linear_Programming_-_Ice_Cream_Blending.pdf
6•ok123456•2d ago•1 comments

Shelf Source: Tom MacWright

https://roadlessread.com/views/ss-macwright
13•tobr•1d ago•0 comments

Idempotency is easy until the second request is different

https://blog.dochia.dev/blog/idempotency/
305•ludovicianul•3d ago•181 comments

Gode Cookery – Authentic Medieval Recipes

http://www.godecookery.com/godeboke/godeboke.htm
12•Mr_Minderbinder•3d ago•1 comments

Walking slower? Your ears, not your knees, might be the problem

https://www.wsj.com/health/wellness/hearing-loss-walking-speed-iphone-study-c53c482a
114•marc__1•1d ago•72 comments

Task Paralysis and AI

https://g5t.de/articles/20260510-task-paralysis-and-ai/index.html
232•MrGilbert•1d ago•113 comments