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

Comments

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

Is BGP Safe Yet? No. Test Your ISP

https://isbgpsafeyet.com/
63•janandonly•1h ago•25 comments

Claude Code Unpacked : A visual guide

https://ccunpacked.dev/
741•autocracy101•9h ago•253 comments

Show HN: Sycamore – next gen Rust web UI library using fine-grained reactivity

https://sycamore.dev
41•lukechu10•1h ago•28 comments

CERN levels up with new superconducting karts

https://home.cern/news/news/engineering/cern-levels-new-superconducting-karts
246•fnands•6h ago•52 comments

Show HN: Baton – A desktop app for developing with AI agents

https://getbaton.dev/
24•tordrt•2h ago•23 comments

Intuiting Pratt Parsing

https://louis.co.nz/2026/03/26/pratt-parsing.html
74•signa11•2d ago•17 comments

Show HN: CLI to order groceries via reverse-engineered REWE API (Haskell)

https://github.com/yannick-cw/korb
138•wazHFsRy•2d ago•53 comments

Consider the Greenland Shark (2020)

https://www.lrb.co.uk/the-paper/v42/n09/katherine-rundell/consider-the-greenland-shark
23•mooreds•5d ago•1 comments

Claude Wrote a Full FreeBSD Remote Kernel RCE with Root Shell (CVE-2026-4747)

https://github.com/califio/publications/blob/main/MADBugs/CVE-2026-4747/write-up.md
125•ishqdehlvi•9h ago•40 comments

Wasmer (YC S19) Is Hiring – Rust and DevRel Positions

https://www.workatastartup.com/companies/wasmer
1•syrusakbary•2h ago

New Patches Allow Building Linux IPv6-Only, Option to Deprecate "Legacy" IPv4

https://www.phoronix.com/news/Linux-IPv6-IPv4-Legacy-Knobs
34•Bender•1h ago•3 comments

Chess in SQL

https://www.dbpro.app/blog/chess-in-pure-sql
110•upmostly•3d ago•24 comments

A dot a day keeps the clutter away

https://scottlawsonbc.com/post/dot-system
421•scottlawson•17h ago•125 comments

Show HN: 1-Bit Bonsai, the First Commercially Viable 1-Bit LLMs

https://prismml.com/
326•PrismML•17h ago•131 comments

TinyLoRA – Learning to Reason in 13 Parameters

https://arxiv.org/abs/2602.04118
206•sorenjan•5d ago•33 comments

I Quit. The Clankers Won

https://dbushell.com/2026/04/01/i-quit-the-clankers-won/
225•domysee•5h ago•222 comments

TruffleRuby

https://chrisseaton.com/truffleruby/
160•tosh•3d ago•18 comments

MiniStack (replacement for LocalStack)

https://ministack.org/
261•kerblang•17h ago•50 comments

The Claude Code Source Leak: fake tools, frustration regexes, undercover mode

https://alex000kim.com/posts/2026-03-31-claude-code-source-leak/
1266•alex000kim•1d ago•512 comments

Bring Back MiniDV with This Raspberry Pi FireWire Hat

https://www.jeffgeerling.com/blog/2026/minidv-with-raspberry-pi-firewire-hat/
87•ingve•3d ago•15 comments

Neanderthals survived on a knife's edge for 350k years

https://www.science.org/content/article/neanderthals-survived-knife-s-edge-350-000-years
190•Hooke•13h ago•144 comments

Slop is not necessarily the future

https://www.greptile.com/blog/ai-slopware-future
273•dakshgupta•23h ago•446 comments

4D Doom

https://github.com/danieldugas/HYPERHELL
242•chronolitus•4d ago•58 comments

OpenAI closes funding round at an $852B valuation

https://www.cnbc.com/2026/03/31/openai-funding-round-ipo.html
486•surprisetalk•18h ago•444 comments

Open source CAD in the browser (Solvespace)

https://solvespace.com/webver.pl
352•phkahler•1d ago•111 comments

6o6 v1.1: Faster 6502-on-6502 virtualization for a C64/Apple II Apple-1 emulator

http://oldvcr.blogspot.com/2026/03/6o6-v11-faster-6502-on-6502.html
25•classichasclass•3d ago•1 comments

Axios compromised on NPM – Malicious versions drop remote access trojan

https://www.stepsecurity.io/blog/axios-compromised-on-npm-malicious-versions-drop-remote-access-t...
1881•mtud•1d ago•759 comments

In Case of Emergency, Make Burrito Bison 3 (2017)

https://juicybeast.com/2017/08/03/in-case-of-emergency-make-burrito-bison-3/
19•amarcheschi•1d ago•8 comments

Teenage Engineering's PO-32 acoustic modem and synth implementation

https://github.com/ericlewis/libpo32
132•ericlewis•4d ago•27 comments

Show HN: Postgres extension for BM25 relevance-ranked full-text search

https://github.com/timescale/pg_textsearch
172•tjgreen•21h ago•47 comments