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

Comments

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

Montana Leads the Nation with Groundbreaking Right to Compute Act

https://www.westernmt.news/2025/04/21/montana-leads-the-nation-with-groundbreaking-right-to-compu...
41•bilsbie•1h ago•21 comments

1M context is now generally available for Opus 4.6 and Sonnet 4.6

https://claude.com/blog/1m-context-ga
954•meetpateltech•22h ago•372 comments

AI Didn't Simplify Software Engineering: It Just Made Bad Engineering Easier

https://robenglander.com/writing/ai-did-not-simplify/
60•birdculture•59m ago•34 comments

Baochip-1x: What It Is, Why I'm Doing It Now and How It Came About

https://www.crowdsupply.com/baochip/dabao/updates/what-it-is-why-im-doing-it-now-and-how-it-came-...
150•timhh•2d ago•18 comments

XML Is a Cheap DSL

https://unplannedobsolescence.com/blog/xml-cheap-dsl/
153•y1n0•3h ago•121 comments

Python: The Optimization Ladder

https://cemrehancavdar.com/2026/03/10/optimization-ladder/
95•Twirrim•3d ago•20 comments

Megadev: A Development Kit for the Sega Mega Drive and Mega CD Hardware

https://github.com/drojaazu/megadev
65•XzetaU8•6h ago•1 comments

Cookie Jars Capture American Kitsch (2023)

https://www.eater.com/23651631/cookie-jar-trend-appreciation-collecting-history
4•NaOH•22h ago•0 comments

9 Mothers Defense (YC P26) Is Hiring in Austin

https://jobs.ashbyhq.com/9-mothers?utm_source=x8pZ4B3P3Q
1•ukd1•2h ago

Wired headphone sales are exploding

https://www.bbc.com/future/article/20260310-wired-headphones-are-better-than-bluetooth
272•billybuckwheat•2d ago•479 comments

Starlink Militarization and Its Impact on Global Strategic Stability

https://interpret.csis.org/translations/starlink-militarization-and-its-impact-on-global-strategi...
33•msuniverse2026•6h ago•18 comments

Philosoph Jürgen Habermas Gestorben

https://www.spiegel.de/kultur/philosoph-juergen-habermas-mit-96-jahren-gestorben-a-8be73ac7-e722-...
45•sebastian_z•1h ago•10 comments

Show HN: Channel Surfer – Watch YouTube like it’s cable TV

https://channelsurfer.tv
559•kilroy123•3d ago•165 comments

The Isolation Trap: Erlang

https://causality.blog/essays/the-isolation-trap/
103•enz•2d ago•38 comments

Nominal Types in WebAssembly

https://wingolog.org/archives/2026/03/10/nominal-types-in-webassembly
13•ingve•4d ago•2 comments

Mouser: An open source alternative to Logi-Plus mouse software

https://github.com/TomBadash/MouseControl
383•avionics-guy•21h ago•120 comments

RAM kits are now sold with one fake RAM stick alongside a real one

https://www.tomshardware.com/pc-components/ram/fake-ram-bundled-with-real-ram-to-create-a-perform...
117•edward•5h ago•96 comments

Hammerspoon

https://github.com/Hammerspoon/hammerspoon
317•tosh•21h ago•116 comments

Digg is gone again

https://digg.com/
294•hammerbrostime•20h ago•295 comments

Michael Faraday: Scientist and Nonconformist (1996)

http://silas.psfc.mit.edu/Faraday/
30•o4c•3d ago•3 comments

Show HN: Ink – Deploy full-stack apps from AI agents via MCP or Skills

https://ml.ink/
8•august-•3d ago•0 comments

Can I run AI locally?

https://www.canirun.ai/
1316•ricardbejarano•1d ago•321 comments

Recursive Problems Benefit from Recursive Solutions

https://jnkr.tech/blog/recursive-benefits-recursive
38•luispa•3d ago•20 comments

I found 39 Algolia admin keys exposed across open source documentation sites

https://benzimmermann.dev/blog/algolia-docsearch-admin-keys
143•kernelrocks•16h ago•42 comments

A Survival Guide to a PhD (2016)

http://karpathy.github.io/2016/09/07/phd/
144•vismit2000•4d ago•89 comments

Secure Secrets Management for Cursor Cloud Agents

https://infisical.com/blog/secure-secrets-management-for-cursor-cloud-agents
25•vmatsiiako•4d ago•4 comments

I beg you to follow Crocker's Rules, even if you will be rude to me

https://lr0.org/blog/p/crocker/
108•ghd_•16h ago•166 comments

The Forth Language [Byte Magazine Volume 05 Number 08]

https://archive.org/details/byte-magazine-1980-08
23•AlexeyBrin•3h ago•2 comments

Atari 2600 BASIC Programming (2015)

https://huguesjohnson.com/programming/atari-2600-basic/
41•mondobe•2d ago•9 comments

Games with loot boxes to get minimum 16 age rating across Europe

https://www.bbc.com/news/articles/cge84xqjg5lo
270•gostsamo•15h ago•174 comments