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";
  }

Show HN: PVAC FHE over hypergraphs with LPN security

https://github.com/octra-labs/pvac_hfhe_cpp
1•0x0ffh_local•5m ago•0 comments

The GBible – backup your files properly to Google Drive and/or S3

https://docs.google.com/document/d/11_mCt1XWlTlXzhs-zo1yU6sAGcKTXOAdWO5IzRiD_KE/edit?tab=t.0
2•cjv•7m ago•0 comments

MicroVault: A simple distributed blob store in ~1000 lines

1•afpereira•10m ago•0 comments

Built a Request Path Simulator – mock DNS records and simulate redirect hops

https://jsonyaml.com/tools/request-path-simulator
1•buildpotential•13m ago•0 comments

YouTuber still banned despite defeating YT in lawsuit over AI banning channel

https://www.dexerto.com/youtube/youtuber-still-banned-despite-defeating-youtube-in-lawsuit-over-a...
1•dataflow•14m ago•0 comments

What are you working on? (Dec 2025)

1•burgerquizz•15m ago•0 comments

How much of "Mississippi's education miracle" is an artifact of selection bias?

https://statmodeling.stat.columbia.edu/2025/12/01/how-much-of-mississippis-education-miracle-is-a...
1•Anon84•22m ago•0 comments

3D printed titanium Apple Watch cases

https://www.apple.com/newsroom/2025/11/mapping-the-future-with-3d-printed-titanium-apple-watch-ca...
2•ndr42•22m ago•3 comments

Jonbar Hinge

https://en.wikipedia.org/wiki/Jonbar_hinge
2•surprisetalk•23m ago•0 comments

You've (Likely) Been Playing the Game of Life Wrong [video]

https://www.youtube.com/watch?v=HBluLfX2F_k
1•surprisetalk•23m ago•0 comments

Show HN: Roampal – a local memory layer that learns from outcomes

https://github.com/roampal-ai/roampal
1•roampal•24m ago•0 comments

In the Shadow of Jane Street and Citadel Securities, Hudson River Mints Billions

https://www.bloomberg.com/news/features/2025-12-01/high-speed-trader-hudson-river-steps-up-battle...
1•petethomas•24m ago•0 comments

Anthropic: AI agents find $4.6M in blockchain smart contract exploits

https://red.anthropic.com/2025/smart-contracts/
4•bpierre•25m ago•0 comments

Costco Joins Companies Suing for Refunds If Tariffs Fall

https://www.bloomberg.com/news/articles/2025-12-01/costco-joins-companies-suing-for-refunds-if-tr...
2•petethomas•26m ago•0 comments

After another failure, this Russian ICBM is "unique" in its unreliability

https://arstechnica.com/space/2025/12/the-missile-meant-to-strike-fear-in-russias-enemies-fails-o...
2•doener•27m ago•0 comments

The Devil's Plan to Ruin the Next Generation

https://www.afterbabel.com/p/the-devils-plan-to-ruin-the-next
2•jdkee•27m ago•0 comments

Show HN: Simweb is a discrete-event simulation for web processes

https://github.com/yunier-rojas/simweb
1•yunier-rojas•27m ago•0 comments

Ask HN: What alternatives to Docker Desktop are people using?

1•prdonahue•27m ago•0 comments

Complex end-to-end tests using Guix G-expressions

https://systemreboot.net/post/complex-end-to-end-tests-using-guix-g-expressions.html
1•todsacerdoti•29m ago•0 comments

Isabel Allende wrote her first novel almost by accident [video]

https://www.bbc.com/video/bbc-maestro/isabel-allende
1•nhatcher•30m ago•0 comments

The College Students Who Can't Do Elementary Math

https://www.wsj.com/opinion/the-college-students-who-cant-do-elementary-math-2db5e549
3•cypherpunks01•33m ago•1 comments

What You See Is What It Does: A Structural Pattern for Legible Software

https://dl.acm.org/doi/10.1145/3759429.3762628
1•PaulHoule•36m ago•0 comments

Yamada to sell 'human washing machine' after expo popularity

https://www.japantimes.co.jp/business/2025/11/27/companies/yamada-human-washing-machine-sale/
1•doener•37m ago•1 comments

Bluefox NX1 User Review

https://old.reddit.com/r/smallphones/comments/1pbimn2/bluefox_nx1_review/
1•maelito•39m ago•0 comments

MSTR Establishes $1.44B Cash Reserve, Slashes 2025 Profit, BTC Yield Targets

https://www.coindesk.com/markets/2025/12/01/strategy-establishes-usd1-44b-cash-reserve-slashes-20...
2•donsupreme•39m ago•0 comments

Today in History: December 1, Rosa Parks refuses to give up bus seat

https://apnews.com/today-in-history/december-1
1•petethomas•40m ago•0 comments

Show HN: MCP Traffic Analyze with NPM

https://www.npmjs.com/package/@mcp-shark/mcp-shark
11•o4isec•42m ago•0 comments

Setting a wallpaper with less than 250 Kb

https://www.lgfae.com/posts/2025-11-21-SettingAWallpaperWithLessThan250KB.html
1•birdculture•43m ago•0 comments

Hack Club strikes a promotion deal with Hacker News

1•Agreed3750•46m ago•0 comments

Novelty Automation: A collection of satirical home-made arcade machines

https://novelty-automation.com/
2•nanomonkey•48m ago•1 comments