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

Comments

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

Why one of the nation's most prosperous industries is shedding jobs

https://www.washingtonpost.com/business/2025/11/18/big-tech-layoffs-ai/
1•jackallis•27s ago•0 comments

A City Is Broke. Can a Billionaires' Urbanist Dream Offer It a Last Chance?

https://www.nytimes.com/2025/11/18/business/economy/suisun-city-makes-an-offer-to-california-fore...
1•mitchbob•55s ago•1 comments

Feeling Flush with Success – Making Museum Bathrooms into Exhibition Spaces

https://blog.orselli.net/2025/07/feeling-flush-with-success-making.html
1•ripe•56s ago•0 comments

The Connectivity Standards Alliance Announces Zigbee 4.0 and Suzi

https://csa-iot.org/newsroom/the-connectivity-standards-alliance-announces-zigbee-4-0-and-suzi-em...
1•paulatreides•5m ago•0 comments

MPEG: Setting the Standards for a Digital Future

https://computeradsfromthepast.substack.com/p/mpeg-setting-the-standards-for-a
1•rbanffy•6m ago•0 comments

Mac Mini M4 Storage Upgrade: My Take on the Acasis M001 vs. WD SN7100 NVMe

https://wasi0013.com/2025/11/18/mac-mini-m4-storage-upgrade-my-honest-take-on-the-acasis-m001-and...
1•furkansahin•6m ago•0 comments

Optimizing RhBMP-2 Therapy for Bone Regeneration

https://www.mdpi.com/1422-0067/26/21/10723
1•PaulHoule•7m ago•0 comments

Color Palette Pro

https://colorpalette.pro/
1•cal85•8m ago•0 comments

Old 'Ghost' Theory of Quantum Gravity Makes a Comeback

https://www.quantamagazine.org/old-ghost-theory-of-quantum-gravity-makes-a-comeback-20251117/
1•pseudolus•9m ago•0 comments

Google is collecting troves of data from downgraded Nest thermostats

https://www.theverge.com/news/820600/google-nest-learning-thermostat-downgraded-data-collection
2•sdoering•10m ago•0 comments

High-resolution climate model forecasts a wet, turbulent future

https://www.science.org/content/article/high-resolution-climate-model-forecasts-wet-turbulent-future
1•bikenaga•10m ago•0 comments

Google Antigravity – Agentic development IDE [video]

https://www.youtube.com/watch?v=nTOVIGsqCuY
1•truth_seeker•12m ago•0 comments

Why crypto is melting down and stocks keep falling

https://www.cnn.com/2025/11/18/business/bitcoin-price-crypto-stocks
2•Bender•13m ago•0 comments

The Only AI Explainer You'll Ever Need

https://kemendo.com/Understand-AI.html
2•AndrewKemendo•14m ago•0 comments

Tooltip Components Should Not Exist

https://tkdodo.eu/blog/tooltip-components-should-not-exist
2•agos•14m ago•0 comments

Hey there You are using WhatsApp (enumerating 3B WhatsApp accounts)

https://github.com/sbaresearch/whatsapp-census
1•ano-ther•15m ago•0 comments

Pebble, Rebble, and a Path Forward

https://ericmigi.com/blog/pebble-rebble-and-a-path-forward/
14•phoronixrly•16m ago•1 comments

Rails to SvelteKit Migration – LocallyGrown

https://blog.kestrelsnest.social/posts/locallygrown-rails-svelte-migration/
1•dzonga•18m ago•0 comments

Camper Rental Company Is Selling All of Its Custom Vans

https://www.thedrive.com/news/a-defunct-camper-rental-company-is-selling-all-of-its-custom-vans-a...
3•iancmceachern•19m ago•0 comments

RasterFlow – A lightweight node-based image editor

https://rasterflow.io
2•activey•20m ago•1 comments

Show HN: I am self-hosting a time-sorted list of top STEM, Arts and Design posts

https://limereader.com/
1•busymom0•22m ago•1 comments

Cambridge Dictionary's Word of the Year 2025

https://dictionaryblog.cambridge.org/2025/11/18/cambridge-dictionary-word-of-the-year-2025/
1•ChrisArchitect•22m ago•0 comments

lakeFS Acquires DVC, Uniting Data Version Control Pioneers

https://lakefs.io/media-mentions/lakefs-acquires-dvc-uniting-data-version-control-pioneers/
1•versionninja•22m ago•0 comments

Dissent

https://exple.tive.org/blarg/2025/11/17/dissent/
2•pavel_lishin•24m ago•0 comments

Master System at 40: the truth about Sega's most underrated console

https://www.theguardian.com/games/2025/nov/18/sega-master-system-nintendo-entertainment-system
1•n1b0m•27m ago•0 comments

How to Check If a Company Hires Abroad

https://relocateme.substack.com/p/how-do-you-know-if-a-company-is-open
1•andrewstetsenko•28m ago•0 comments

NIH funding cuts affect over 74,000 people in experiments

https://apnews.com/article/nih-funding-cuts-32b9b7bad01457a5412af26e394e3735
2•gmays•29m ago•0 comments

Dockerlings: Learn Docker in Your Terminal

https://github.com/furkan/dockerlings
1•birdculture•30m ago•0 comments

Ask HN: Why does Y Combinator seem to be consistently funding AI slop?

2•coldtrait•30m ago•1 comments

OpenHands Raised $18.8M to Build the Open Standard for Autonomous Software Dev

https://openhands.dev/blog/weve-just-raised-18-8m-to-build-the-open-standard-for-autonomous-softw...
1•janpio•30m ago•0 comments