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";
  }

They graduated from Stanford. Due to AI, they can't find a job

https://www.latimes.com/business/story/2025-12-19/they-graduated-from-stanford-due-to-ai-they-can...
1•paulpauper•1m ago•0 comments

Becoming a software A-Team via writing culture

https://www.evalapply.org/posts/writing-practices-to-10x-engineering/index.html
1•andsoitis•1m ago•0 comments

Bash-completion: Programmable bash completion

https://github.com/scop/bash-completion
1•flykespice•2m ago•0 comments

January in Servo: preloads, better forms, details styling, and more

https://servo.org/blog/2026/02/28/january-in-servo/
1•birdculture•2m ago•0 comments

Show HN: Chatbot to reuse AI prompts instead of copy-pasting

https://intellex.wasmer.app/homepage/homepage.html
1•owenthecoder13•2m ago•0 comments

The challenges of a weight-loss economy

https://www.ft.com/content/2d73a61b-6328-41af-ad01-279a7195de42
1•paulpauper•3m ago•0 comments

How to power the world 24/7 with geothermal [video]

https://www.youtube.com/watch?v=Xlc_ALDWc0Q
1•simonebrunozzi•3m ago•0 comments

Trump crossed a 'dangerous red line' with killing of supreme leader

https://www.cnn.com/2026/03/01/middleeast/iranian-deputy-foreign-minister-saeed-khatibzadeh-intv-...
2•Bender•4m ago•0 comments

California introduces age verification law for OS, including Linux and SteamOS

https://www.tomshardware.com/software/operating-systems/california-introduces-age-verification-law
2•taubek•6m ago•1 comments

Fighting with Iran has spread to tankers at sea

https://www.businessinsider.com/fight-iran-spread-oil-tankers-vessels-strait-of-hormuz-2026-3
1•geox•7m ago•0 comments

Show HN: Offline dictionary with spaced repetition (Tauri, Svelte): Deft

https://deft.so/
1•L_i_m_n•7m ago•0 comments

The Rust Calling Convention We Deserve

https://mcyoung.xyz/2024/04/17/calling-convention/
1•cratermoon•8m ago•0 comments

Show HN: Call your coding agent from anywhere (Bosun)

https://github.com/virtengine/bosun/releases/tag/0.37.0
1•jaeko44•9m ago•0 comments

The Mountain, the Moon Cave and the Sad God – A Making of [video]

https://www.youtube.com/watch?v=wLTcubTNIl4
1•cyanbane•10m ago•0 comments

The Sunday Signal: Capital Doesn't Lie

https://newsletter.djr.ai/p/the-sunday-signal-capital-doesnt
1•discoinferno•10m ago•0 comments

Stop building AI for the happy path: lessons from the chaos of real-world data

https://www.metabase.com/blog/lessons-learned-building-ai-analytics-agents
1•igor_mart•12m ago•0 comments

Show HN: I built a tool that turns any API into a CLI for agents

https://instantcli.com
2•stugreen13•13m ago•3 comments

Show HN: Panel Panic a Rust/Macroquad/WASM Panel de Pon/Tetris Attack Clone

https://panel-panic.com
1•LarsDu88•14m ago•0 comments

Show HN: Free tools to understand your Claude Code usage (browser, no install)

https://yurukusa.github.io/cc-toolkit/
1•yurukusa•19m ago•0 comments

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

https://maderix.substack.com/p/inside-the-m4-apple-neural-engine
2•zdw•21m ago•0 comments

Ukraine Became a Drone Factory and Invented the Future of War

https://www.newscientist.com/article/2514976-how-ukraine-became-a-drone-factory-and-invented-the-...
3•stevenwoo•22m ago•0 comments

ISO C++ Standards Committee Panel Discussion – CppCon 2025

https://www.youtube.com/watch?v=R2ulYtpV_rs
2•pjmlp•23m ago•0 comments

Jack Dorsey's 4k Job Cuts at Block Arouse Suspicions of AI-Washing

https://www.bloomberg.com/news/articles/2026-03-01/jack-dorsey-s-4-000-job-cuts-at-block-arouse-s...
4•pinewurst•24m ago•1 comments

Show HN: AskVerdict – Multi-agent AI debates for better decisions(~$0.08/debate)

https://www.askverdict.ai
1•thegdsks•26m ago•1 comments

Brain Tumor Survivors Are Forcing a Rethink of Cancer Care

https://www.bloomberg.com/news/articles/2026-02-27/the-science-of-cancer-care-is-being-changed-by...
4•pinewurst•26m ago•1 comments

The cloud just stopped scaling

https://ounapuu.ee/posts/2026/03/01/cloud/
1•LorenDB•27m ago•0 comments

Project Warrior: How Paramount Beat Netflix in $110B Battle for Warner

https://www.ft.com/content/e352b4b3-ecba-4bc2-984f-9e4f3ce8a366
2•ViktorRay•28m ago•2 comments

Cyber attacks launched alongside with U.S.-Israeli military attack on Iran

https://www.reuters.com/business/media-telecom/hackers-hit-iranian-apps-websites-after-us-israeli...
4•giuliomagnifico•28m ago•0 comments

Ask HN: Is demography victim of social media?

2•julienreszka•30m ago•1 comments

Show HN: Situation Tracker – real-time crisis dashboard

https://www.situationtracker.xyz/
2•jayyvk•31m ago•0 comments