frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

Understanding Java's Asynchronous Journey

https://amritpandey.io/understanding-javas-asynchronous-journey/
17•hardasspunk•2mo ago

Comments

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

Energy expenditure and obesity across the economic spectrum

https://www.pnas.org/doi/full/10.1073/pnas.2420902122
1•domofutu•1m ago•0 comments

AI Breaking into Higher Dimension to Mimic Human Brain and Achieve Intelligence

https://www.popularmechanics.com/science/a65397906/human-brain-ai/
1•Bluestein•2m ago•0 comments

Show HN: Tell the world why you unfollowed/muted a social media account

https://tinmute.com/
1•abzgupta•3m ago•0 comments

Is AI the end of coding as we know it, or just another tool?

https://www.aha.io/engineering/articles/is-ai-the-end-of-coding-or-just-another-tool
3•FigurativeVoid•3m ago•1 comments

WordPress Turmoil and the Fair Package Manager

https://thenewstack.io/wordpress-turmoil-and-the-fair-package-manager/
1•CrankyBear•5m ago•0 comments

The Pragmatic Engineer 2025 Survey: What's in your tech stack?

https://newsletter.pragmaticengineer.com/p/the-pragmatic-engineer-2025-survey
3•iLemming•6m ago•1 comments

Graph Continuous Thought Machines

1•Sai-dewa•9m ago•2 comments

Show HN: McClane – Done-for-you lead drops from Facebook group conversations

https://mcclane.super.site/
1•nickalex•10m ago•1 comments

Silicon Valley, à la Française

https://semiwiki.com/artificial-intelligence/358042-silicon-valley-a-la-francaise/
1•rbanffy•11m ago•0 comments

Energy expenditure and obesity across the economic spectrum

https://www.pnas.org/doi/10.1073/pnas.2420902122
1•bookofjoe•13m ago•0 comments

TikTok Creator Sued by Sylvanian Doll Maker over Brand Promotions

https://www.independent.ie/business/irish/sylvanian-families-toy-firm-in-settlement-talks-with-kildare-tiktok-star-over-parody-videos-featuring-japanese-companys-dolls/a1813361842.html
1•valgaze•14m ago•0 comments

Ask HN: Time to Pivot Out of Engineering?

1•bdnsj•14m ago•0 comments

Where's Firefox Going Next?

https://connect.mozilla.org/t5/discussions/where-s-firefox-going-next-you-tell-us/m-p/100698#M39094
2•ReadCarlBarks•15m ago•0 comments

Views of the U.S. have worsened while opinions of China have improved in surveys

https://www.pewresearch.org/short-reads/2025/07/15/views-of-the-us-have-worsened-while-opinions-of-china-have-improved-in-many-surveyed-countries/
5•alphabetatango•17m ago•1 comments

BlackRock hit by $52B withdrawal from single client

https://www.thetimes.com/business-money/companies/article/blackrock-hit-by-52bn-withdrawal-from-single-client-kmsmg87jc
2•alexcos•18m ago•1 comments

Tried Comet: Impressive AI Tool with Concerns About Future Risks

https://twitter.com/TenZorroAI/status/1945224617859113401
1•paulo20223•20m ago•1 comments

Power-seeking, by any person, may be equivalent to minimizing uncertainty

https://www.lesswrong.com/posts/KYxpkoh8ppnPfmuF3/power-seeking-minimising-free-energy
1•OgsyedIE•20m ago•0 comments

Ask HN: Why Marketing Software Hasn't Had Its 'Cursor Moment' Yet

1•richbelt•22m ago•2 comments

Fighting Brandolini's Law with Sampling

https://brady.fyi/fact-checking/
1•h-bradio•23m ago•0 comments

Differential geometry of ML: a geometric interpretation of gradient descent

https://research.fal.ai/blog/differential-geometry-of-ml/
1•felineflock•23m ago•0 comments

Sci-Fi, Fantasy, Fandom in the Norman vs. Lamb Gothic Fantasy Collection

https://internetarchivecanada.org/2025/07/15/science-fiction-fantasy-and-fandom-in-the-norman-v-lamb-gothic-fantasy-collection/
2•lintalist•26m ago•1 comments

Hacker Residency in Da Nang Vietnam with Tony Dinh

https://www.hackerresidencygroup.com
1•transitivebs•27m ago•1 comments

Cambridge academic James Orr: England should be ethnically English [video]

https://www.youtube.com/watch?v=UngibqLwJ34
2•donsupreme•28m ago•1 comments

Product Innovation is Discovery not Creation

https://boz.com/articles/product-discovery
1•pizzathyme•30m ago•0 comments

Mastodon 4.4 Is Here

https://www.patreon.com/posts/mastodon-4-4-is-134090971
3•doener•31m ago•0 comments

After a Decade of Chaos, Google Is Finally Getting Its Act Together

https://gizmodo.com/after-a-decade-of-chaos-google-is-finally-getting-its-act-together-2000629697
1•mikece•31m ago•1 comments

How to Cool Down Computers Inside of an A320 [video]

https://www.youtube.com/watch?v=HQuc_HhW6VA
1•sarimkx•33m ago•0 comments

Investigation confirms majority of community grievances in Socfin plantations

https://news.mongabay.com/short-article/two-year-investigation-confirms-majority-of-community-grievances-in-socfin-plantations/
1•PaulHoule•34m ago•0 comments

AWS launches Kiro, an agentic AI IDE

https://www.techradar.com/pro/aws-launches-kiro-an-agentic-ai-ide-to-end-the-chaos-of-vibe-coding
1•mikece•35m ago•0 comments

The FIPS 140-3 Go Cryptographic Module

https://go.dev/blog/fips140
4•FiloSottile•36m ago•0 comments