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

Comments

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

Stop Doom Scrolling, Start Doom Coding: Build via the terminal from your phone

https://github.com/rberg27/doom-coding
45•rbergamini27•38m ago•26 comments

Vienam bans unskippable ads

https://saigoneer.com/vietnam-news/28652-vienam-bans-unskippable-ads,-requires-skip-button-to-app...
723•hoherd•3h ago•364 comments

Spherical Snake

https://kevinalbs.com/spherical_snake/
31•subset•5d ago•11 comments

Passing of Joe Mancuso author of Masonite (Python web framework)

https://github.com/MasoniteFramework/masonite/discussions/853
50•wilsonfiifi•2h ago•3 comments

Dude, where's my supersonic jet?

https://rationaloptimistsociety.substack.com/p/dude-wheres-my-supersonic-jet
40•noleary•2h ago•114 comments

Show HN: Jax-JS, array library in JavaScript targeting WebGPU

https://ss.ekzhang.com/p/jax-js-an-ml-library-for-the-web
52•ekzhang•1h ago•6 comments

Show HN: Prism.Tools – Free and privacy-focused developer utilities

https://blgardner.github.io/prism.tools/
273•BLGardner•7h ago•82 comments

enclose.horse

https://enclose.horse/
965•DavidSJ•14h ago•171 comments

Launch HN: Tamarind Bio (YC W24) – AI Inference Provider for Drug Discovery

28•denizkavi•2h ago•11 comments

Why agents matter more than other AI

https://substack.com/home/post/p-182047799
24•nvader•19h ago•6 comments

High-Performance DBMSs with io_uring: When and How to use it

https://arxiv.org/abs/2512.04859
11•matt_d•47m ago•0 comments

Loongarch Improvements with Box64

https://box86.org/2026/01/new-box64-v0-4-0-released/
41•aaronday•3h ago•1 comments

My Tamagotchi is an RL agent playing Slither.io

https://nkasmanoff.github.io/#/blog/tamagotchi-rl-slitherio
23•nkaz123•13h ago•11 comments

Why Big Companies Keep Failing: The Stack Fallacy (2016)

https://techcrunch.com/2016/01/18/why-big-companies-keep-failing-the-stack-fallacy/
34•bobbiechen•3h ago•13 comments

I wanted a camera that doesn't exist – so I built it

https://medium.com/@cristi.baluta/i-wanted-a-camera-that-doesnt-exist-so-i-built-it-5f9864533eb7
157•cyrc•4d ago•50 comments

Creating a Bespoke Data Diode for Air‑Gapped Networks

https://nelop.com/bespoke-data-diode-airgap/
26•nelop•2h ago•28 comments

Hierarchical Autoregressive Modeling for Memory-Efficient Language Generation

https://arxiv.org/abs/2512.20687
16•PaulHoule•2h ago•0 comments

Using fewer syllables to express numbers

https://thegraycuber.github.io/fast_numbers
16•adrianton3•2d ago•14 comments

Video Game Websites in the early 00s

https://www.webdesignmuseum.org/exhibitions/video-game-websites-in-the-early-00s
16•klaussilveira•1h ago•7 comments

High-performance header-only container library for C++23 on x86-64

https://github.com/kressler/fast-containers
56•mattgodbolt•5h ago•14 comments

Show HN: Mantic.sh – Search 480k files in 0.46s without embeddings

https://github.com/marcoaapfortes/Mantic.sh
4•marcoaapfortes•6h ago•1 comments

Why is the Gmail app 700 MB?

https://akr.am/blog/posts/why-is-the-gmail-app-700-mb
226•thefilmore•3h ago•225 comments

Locating a Photo of a Vehicle in 30 Seconds with GeoSpy

https://geospy.ai/blog/locating-a-photo-of-a-vehicle-in-30-seconds-with-geospy
50•kachapopopow•2h ago•53 comments

Volkswagen Brings Back Physical Buttons

https://www.caranddriver.com/news/a69916699/volkswagen-interior-physical-buttons-return/
193•stephc_int13•3h ago•153 comments

Show HN: Stash – Sync Markdown Files with Apple Notes via CLI

https://github.com/shakedlokits/stash
33•shuka•3h ago•11 comments

AWS raises GPU prices 15% on a Saturday, hopes you weren't paying attention

https://www.theregister.com/2026/01/05/aws_price_increase/
604•Brajeshwar•8h ago•405 comments

Gemini Protocol Deployment Statistics

https://www.obsessivefacts.com/gemini-proxy?uri=gemini%3A%2F%2Fgemini.bortzmeyer.org%2Fsoftware%2...
61•rickcarlino•5h ago•8 comments

Repair a ship’s hull still in the river in -50˚C (2022)

https://eugene.kaspersky.com/2022/04/26/how-to-repair-the-underside-of-a-ships-hull-still-in-the-...
193•aziaziazi•4d ago•49 comments

Show HN: ccrider - Search and Resume Your Claude Code Sessions – TUI / MCP / CLI

https://github.com/neilberkman/ccrider
9•nberkman•6h ago•0 comments

65% of Hacker News posts have negative sentiment, and they outperform

https://philippdubach.com/standalone/hn-sentiment/
421•7777777phil•5h ago•414 comments