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

God Sleeps in the Minerals

https://wchambliss.wordpress.com/2026/03/03/god-sleeps-in-the-minerals/
189•speckx•3h ago•53 comments

Show HN: Every CEO and CFO change at US public companies, live from SEC

https://tracksuccession.com/explore
114•porsche959•3h ago•45 comments

Want to Write a Compiler? Just Read These Two Papers (2008)

https://prog21.dadgum.com/30.html
311•downbad_•6h ago•94 comments

Good Sleep, Good Learning (2012)

https://super-memory.com/articles/sleep.htm
227•downbad_•6h ago•114 comments

Gemini Robotics-ER 1.6

https://deepmind.google/blog/gemini-robotics-er-1-6/
86•markerbrod•2h ago•15 comments

The Future of Everything Is Lies, I Guess: New Jobs

https://aphyr.com/posts/419-the-future-of-everything-is-lies-i-guess-new-jobs
125•aphyr•2h ago•79 comments

Costasiella kuroshimae – Solar Powered animals, that do indirect photosynthesis

https://en.wikipedia.org/wiki/Costasiella_kuroshimae
96•vinnyglennon•3d ago•39 comments

Your Backpack Got Worse on Purpose

https://www.worseonpurpose.com/p/your-backpack-got-worse-on-purpose
179•113•5h ago•156 comments

Wacli – WhatsApp CLI

https://github.com/steipete/wacli
176•dinakars777•9h ago•124 comments

Fixing a 20-year-old bug in Enlightenment E16

https://iczelia.net/posts/e16-20-year-old-bug/
217•snoofydude•11h ago•114 comments

Metro stop is Ancient Rome's new attraction

https://www.bbc.com/travel/article/20260408-a-150-metro-ticket-to-ancient-rome
72•Stevvo•5d ago•13 comments

We ran Doom on a 40 year old printer controller (Agfa Compugraphic 9000PS) [video]

https://www.youtube.com/watch?v=cltnlks2-uU
26•zdw•3d ago•5 comments

Google Gemma 4 Runs Natively on iPhone with Full Offline AI Inference

https://www.gizmoweek.com/gemma-4-runs-iphone/
192•takumi123•10h ago•129 comments

Proliferate (YC S25) Is Hiring Founding Engineers

https://www.ycombinator.com/companies/proliferate/jobs/L3copvK-founding-engineer
1•pablo24602•4h ago

Pretty Fish: A better mermaid diagram editor

https://pretty.fish/
60•pastelsky•5d ago•13 comments

Do you even need a database?

https://www.dbpro.app/blog/do-you-even-need-a-database
43•upmostly•3h ago•72 comments

Forcing an Inversion of Control on the SaaS Stack

https://www.100x.bot/a/client-side-injection-inversion-of-control-saas
7•shardullavekar•4d ago•2 comments

US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf]

https://fingfx.thomsonreuters.com/gfx/legaldocs/xmvjyjekkpr/Rakoff%20-%20order%20-%20AI.pdf
56•1vuio0pswjnm7•2h ago•34 comments

Elevated errors on Claude.ai, API, Claude Code

https://claudestatus.com/
173•redm•1h ago•146 comments

Allbirds, Inc. Announces Expansion into AI Compute Infrastructure

https://ir.allbirds.com/news-releases/news-release-details/allbirds-inc-executes-50m-convertible-...
40•dmajka•3h ago•26 comments

Academic fraud may be the symptom of a more systemic problem

https://www.voxweb.nl/en/academic-fraud-may-be-the-symptom-of-a-much-more-systemic-problem
30•the-mitr•5h ago•24 comments

MCP as Observability Interface: Connecting AI Agents to Kernel Tracepoints

https://ingero.io/mcp-observability-interface-ai-agents-kernel-tracepoints/
31•ingero_io•2h ago•12 comments

AI ruling prompts warnings from US lawyers: Your chats could be used against you

https://www.reuters.com/legal/government/ai-ruling-prompts-warnings-us-lawyers-your-chats-could-b...
70•alephnerd•3h ago•37 comments

Anna's Archive loses $322M Spotify piracy case without a fight

https://torrentfreak.com/annas-archive-loses-322-million-spotify-piracy-case-without-a-fight/
69•askl•8h ago•75 comments

Study: Back-to-basics approach can match or outperform AI in language analysis

https://www.manchester.ac.uk/about/news/back-to-basics-approach-can-match-or-outperform-ai/
12•giuliomagnifico•3h ago•3 comments

New Modern Greek

https://redas.dev/NewModernGreek/
6•holoflash•2d ago•6 comments

Dependency cooldowns turn you into a free-rider

https://calpaterson.com/deps.html
161•pabs3•14h ago•111 comments

MIT Radiation Laboratory

https://www.ll.mit.edu/about/history/mit-radiation-laboratory
29•stmw•3d ago•7 comments

My adventure in designing API keys

https://vjay15.github.io/blog/apikeys/
94•vjay15•3d ago•70 comments

A communist Apple II and fourteen years of not knowing what you're testing

https://llama.gs/blog/index.php/2026/04/10/friday-archaeology-a-communist-apple-ii-and-fourteen-y...
219•major4x•4d ago•100 comments