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

Comments

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

Zwift buys Rouvy in shake-up of indoor cycling

https://www.bikeradar.com/news/zwift-buys-rouvy-in-massive-shake-up-of-indoor-cycling
1•obilgic•1m ago•0 comments

Claude.ai and API Unavailable

https://status.claude.com/incidents/2gf1jpyty350
4•rob•1m ago•0 comments

Claude.ai Down Again?

2•zh_code•2m ago•2 comments

45% of Hostile Bot Traffic Passes Your WAF. Here's Why

https://botconduct.org/waf-baypass-45-percent/
1•botconduct•2m ago•0 comments

AirDrop is coming to more Android phones, and I'm here for it

https://9to5mac.com/2026/04/29/airdrop-is-now-widely-available-on-android-phones-and-im-here-for-it/
2•omer_k•10m ago•0 comments

Serra – A Magic: The Gathering life counter using DRM/KMS

https://git.sr.ht/~cmt/serra
1•nan60•11m ago•0 comments

Qualcomm, Apple, and Nuvia alumni form CPU startup – Nuvacore

https://www.tomshardware.com/pc-components/cpus/legendary-qualcomm-apple-and-nuvia-alumni-form-ne...
1•gnabgib•11m ago•0 comments

Show HN: SigMap – 81.1% retrieval hit 5, 96.9% token reduce,zero deps

https://github.com/manojmallick/sigmap
1•manoj079•19m ago•0 comments

Gen Z is outsourcing hard conversations to AI. Why it matters

https://www.rnz.co.nz/life/relationships/gen-z-is-outsourcing-hard-conversations-to-ai-why-it-mat...
3•billybuckwheat•20m ago•0 comments

Joby Kicks Off NYC Electric Air Taxi Demos with Historic JFK Flight

https://www.flyingmag.com/joby-nyc-electric-air-taxi-jfk-airport/
2•Jblx2•20m ago•0 comments

Dex Raised $5.3M to Hire Your AI Engineers Without the LinkedIn Parade

https://www.siliconsnark.com/dex-raised-5-3m-to-hire-your-ai-engineers-without-the-linkedin-parade/
1•SaaSasaurus•22m ago•1 comments

Mike: open-source legal AI

https://mikeoss.com/
2•noleary•26m ago•0 comments

Google to sell TPU chips to 'select' customers in latest shot at Nvidia

https://finance.yahoo.com/markets/stocks/article/google-to-sell-tpu-chips-to-select-customers-in-...
2•wslh•30m ago•0 comments

100k-Year Problem

https://en.wikipedia.org/wiki/100,000-year_problem
1•red369•31m ago•0 comments

China pushes EU capitals to scrap 'Made in Europe' law or face retaliation

https://www.euronews.com/my-europe/2026/04/29/china-pushes-eu-capitals-to-scrap-made-in-europe-la...
5•ericmay•32m ago•0 comments

Integer Overflow Checking Cost

https://danluu.com/integer-overflow/
1•iwsk•34m ago•1 comments

Meta Shares Plunge as AI Investments Raise Spending Outlook [video]

https://www.youtube.com/watch?v=4z5OA-NFtgQ
1•mgh2•34m ago•0 comments

Sophie Germain and Prime Numbers – James Maynard (Oxford Mathematics) [video]

https://www.youtube.com/watch?v=yq4zHsdOy54
1•vismit2000•35m ago•0 comments

Efficient Video Intelligence in 2026

https://v-chandra.github.io/efficient-video-intelligence/
1•gmays•39m ago•0 comments

Digital Nomads: In Somaliland where 95% of the country has internet (2020)

https://techcabal.com/2020/03/20/digital-nomads-somaliland/
2•warbaker•41m ago•0 comments

LLMs are the worlds most powerful autocomplete

https://alfredvc.no/blog/intro-what-is-an-llm
1•alfredvc•42m ago•0 comments

Your Rust Clippy Config Should Be Stricter

https://emschwartz.me/your-clippy-config-should-be-stricter/
1•emschwartz•42m ago•0 comments

Software Developers Are Replacing Software Engineers

https://newsletter.productdriven.com/p/software-developers-are-replacing
2•spo81rty•42m ago•0 comments

Anthropic could raise a new $50B round at a valuation of $900B

https://techcrunch.com/2026/04/29/sources-anthropic-could-raise-a-new-50b-round-at-a-valuation-of...
2•ZeidJ•43m ago•0 comments

A.I. Bots Told Scientists How to Make Biological Weapons

https://www.nytimes.com/2026/04/29/us/ai-chatbots-biological-weapons.html
1•wslh•43m ago•2 comments

The crystals that wiped out an HIV medication, almost overnight [video]

https://www.youtube.com/watch?v=ksn5yrsC3Wg
2•FridayoLeary•45m ago•0 comments

Chloe vs. History: AI influencers are here.

https://www.youtube.com/channel/UCZB1r1In9RfE7tpVrYgcjLQ
2•WheelsAtLarge•49m ago•1 comments

Transcomputational Problem

https://en.wikipedia.org/wiki/Transcomputational_problem
1•jonbaer•49m ago•0 comments

Naval Ravikant: Apple is dead, SaaS is next, you have 18 months

https://twitter.com/mustufa4socials/status/2049518414377480218
4•jbredeche•52m ago•1 comments

Glitch Image Generator

https://blog.adafruit.com/2026/04/29/glitch-image-generator
1•omer_k•52m ago•0 comments