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.

Math Grid – Japan's 100-square math drill (hyakumasu keisan)

https://apps.apple.com/ca/app/math-grid-100-squares/id6779562830
1•emile_labs•4m ago•0 comments

Cutting China reliance would cost the West $23T, research suggests

https://www.ft.com/content/c6c1f5a5-3332-471b-87d5-253e03f8b90a
1•giuliomagnifico•6m ago•0 comments

Gofi – go tooling for Ubiquiti Unifi gear

https://github.com/emergingrobotics/gofi
1•gherlein•7m ago•0 comments

Ampere, open-source battery charge control for Apple Silicon Macs

https://amperebattery.app/
1•elgs•7m ago•1 comments

Recognition of unfamiliar predators in horses through only visual predator cues

https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0349298
1•bookofjoe•8m ago•0 comments

Humans evolved to be twice as big as our ancestors

https://www.newscientist.com/article/2533221-how-humans-evolved-to-be-twice-as-big-as-our-ancestors/
1•ike_usawa•9m ago•0 comments

Neglected software update caused widespread Telstra network outage

https://www.theguardian.com/business/2026/jul/17/telstra-missing-software-update-undocumented-des...
1•prawn•9m ago•0 comments

Get notified about open slots at campgrounds / huts / cabins all over the world

https://getcabinfever.com/en/last-minute
1•felixdoerp•9m ago•0 comments

50 vs. 60 Hz and Alzheimer's Disease, an AI Exploration

https://github.com/mankins/50Hz-vs-60Hz-Alzheimers
1•mankins•11m ago•0 comments

Should AI usage be explicitly disclosed in movies and TV shows?

https://www.unite.ai/should-ai-usage-be-explicitly-disclosed-in-movies-and-tv-shows/
1•50kIters•12m ago•0 comments

Value, quality or growth: three investing philosophies based on 12 years of data

https://aito.ai/blog/value-quality-or-growth-who-was-right/
1•arauhala•12m ago•0 comments

Zero Weights Deterministic Graph Language Model (MSE-GLM)

https://tonlexianert.com/pages/blog.php
1•clifffodokidza•16m ago•0 comments

Ask HN: Best courses/resources to learn SEO?

1•danilovilhena•17m ago•0 comments

Why AI Infrastructure Is Becoming More Important Than AI Models

https://geekyants.com/blog/self-healing-ai-agents-the-future-of-enterprise-automation-needs-gover...
2•maria46•18m ago•0 comments

Blatant AI slop just won a 25k USD DeepMind Kaggle Grand Prize

https://www.kaggle.com/competitions/kaggle-measuring-agi/discussion/724918#3498423
46•twerkmeister•21m ago•4 comments

Show HN: Tiny and CSP-safe expression language for JavaScript

https://github.com/robinvdvleuten/xprsn
1•robinvdvleuten•24m ago•0 comments

Windows XP Simulation by Kimi K3

https://windows-xp.kimi.site/
2•uneven9434•27m ago•0 comments

Ask HN: Whats the worst site that you have encountered for accessibility?

3•a11ymaster•28m ago•1 comments

Get your FREE custom Email

https://bottled.email
2•Spark88•36m ago•2 comments

EU to force Google to share search data and open up AI on Android

https://arstechnica.com/gadgets/2026/07/its-official-eu-will-force-google-to-share-search-data-an...
4•goplayoutside•47m ago•1 comments

Show HN: Vulnsy – A platform for vulnerability management and reporting

https://www.vulnsy.com
1•MrTurvey•49m ago•0 comments

Now, even Russia's most elite hackers are using Clickfix to infect devices

https://arstechnica.com/security/2026/07/now-even-russias-most-elite-hackers-are-using-clickfix-t...
3•joozio•49m ago•0 comments

ScreenWall – Turn old phones into synced widgets for your space

https://screenwall.app/
2•buibuibui•51m ago•0 comments

Soofi – Sovereign Open Source Foundation Models

https://www.soofi.info/
2•sebastian_z•51m ago•0 comments

Rokit to launch what it calls first human kidney regeneration surgery in July

https://www.koreabiomed.com/news/articleView.html?idxno=32016
2•deno•53m ago•0 comments

Show HN: Sandboxd – Self-Hosted Lovable (agents, sandboxes, preview url)

https://github.com/tastyeffectco/sandboxd
2•tastyeffectco•53m ago•1 comments

What Early Hackers Got Right About Today's AI [video]

https://www.youtube.com/watch?v=XHeMsXDyw2A
1•pierrephpguru•1h ago•2 comments

Huawei could become a DRAM fabber

https://www.blocksandfiles.com/ai-ml/2026/07/16/huawei-could-become-a-dram-fabber/5273853
3•rbanffy•1h ago•0 comments

Show HN: Customizable SAP MCP Server

https://superglue.ai/mcp/sap/
1•sfaist•1h ago•0 comments

Comptime Is Funtime: Per-Span State Without a Hash Map

https://david-bach.com/pages/posts/2026-07-15-comptime-is-funtime/index.html
1•eoxxs•1h ago•0 comments