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•1y ago

Comments

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

First ever AI feature film premieres at the Cannes Film Festival

https://www.cgmagonline.com/news/hell-grind-made-only-with-higgsfield-ai/
2•frays•11m ago•0 comments

SpaceX not the behemoth everyone thought

https://www.axios.com/2026/05/21/spacex-ipo-musk-ai
13•kaycebasques•22m ago•0 comments

Israel's arrogance is becoming the evidence in the case against it

https://www.aljazeera.com/opinions/2026/5/21/israels-arrogance-is-becoming-the-evidence-in-the-ca...
3•hebelehubele•23m ago•0 comments

AI workflows: an industry optimising the wrong variables

https://adsurg.substack.com/p/navigating-ai-with-paper-maps
1•adamsurg•23m ago•0 comments

Tell HN: I went to Alaska's northernmost town and this was the GeoIP location

1•ironmagma•28m ago•0 comments

Show HN: TLS Certificate Management and PKI

1•zaitanz•31m ago•0 comments

Newsom intervenes amid historic tech layoffs

https://www.sfgate.com/politics/article/newsom-california-ai-layoffs-22271312.php
3•jimt1234•42m ago•1 comments

Kyle Busch, two-time NASCAR Cup Series champion, dies at age 41

https://www.nascar.com/news-media/2026/05/21/kyle-busch-two-time-nascar-cup-series-champion-dies-...
2•avonmach•47m ago•0 comments

Destiny 2 will no longer be updated

https://twitter.com/destinythegame/status/2057506887600361720
1•azhenley•47m ago•0 comments

SpaceX Fuels More Than 3k% Return for Washington University

https://www.bloomberg.com/news/articles/2026-05-21/spacex-fuels-more-than-3-000-return-for-washin...
1•yakkomajuri•48m ago•0 comments

Show HN: Tight C, a systems language with 10 keywords

https://github.com/alonsovm44/tc-lang/
2•alonsovm44•51m ago•0 comments

Show HN: Roughform, a free Browser-Based 3D Creation Tool

https://roughform.app
1•benhmoore•53m ago•1 comments

Negation Neglect: When models fail to learn negations in training

https://arxiv.org/abs/2605.13829
1•chr15m•58m ago•0 comments

Big Tech software era is over, says top investor James Anderson

https://www.ft.com/content/9d2bd5b3-80c6-49b9-a04b-edc4162c9320
1•1vuio0pswjnm7•59m ago•2 comments

AI Model Inflation: The Unsustainable Subsidy

https://tomtunguz.com/ai-model-inflation/
2•allen-munsch•1h ago•0 comments

Nicotine Patches to Treat Long Covid

https://www.mcgill.ca/oss/article/medical-health-and-nutrition-pseudoscience/strange-story-nicoti...
1•brandonb•1h ago•0 comments

DeepSeek Founder Declares AGI Goal as $10B Round Advances

https://www.bloomberg.com/news/articles/2026-05-22/deepseek-founder-declares-agi-goal-as-10-billi...
1•petethomas•1h ago•1 comments

Americans beware: markets can be out of sync with reality

https://www.ft.com/content/d95ce239-4494-4a94-be43-fc678bc6e1c3
3•petethomas•1h ago•2 comments

Show HN: Spec-Driven Development Workflow for Claude Code

3•sermakarevich•1h ago•0 comments

The fastest manmade object ever was a manhole cover launched by nuke

https://www.wearethemighty.com/mighty-history/fastest-manmade-object/
1•thunderbong•1h ago•1 comments

From Emacs to Agents

https://vivekhaldar.com/articles/from-emacs-to-agents/
1•gandalfgeek•1h ago•0 comments

An Uncharitable Taxonomy of the AI Discourse

https://iceworks.cc/blog/uctd/
1•airhangerf15•1h ago•0 comments

Build Adafruit projects right from Firefox

https://www.firefox.com/en-US/landing/adafruit/
2•mch82•1h ago•0 comments

Alleged Kimwolf Botmaster 'Dort' Arrested, Charged in U.S. and Canada

https://krebsonsecurity.com/2026/05/alleged-kimwolf-botmaster-dort-arrested-charged-in-u-s-and-ca...
3•shepherdjerred•1h ago•0 comments

Residents burn Ebola treatment center in Congo as anger grows over the outbreak

https://www.pbs.org/newshour/world/residents-burn-ebola-treatment-center-in-congo-as-anger-grows-...
1•bryan0•1h ago•0 comments

India Launches Tradable Rainfall Futures Called Rainmumbai

https://www.bloomberg.com/news/articles/2026-05-20/india-gets-first-rainfall-hedge-as-el-nino-thr...
2•samarthr1•1h ago•0 comments

Logging Off

https://user8.bearblog.dev/logging-off/
39•James72689•1h ago•21 comments

Everything Google announced at I/O 2026: Gemini, Android, more

https://9to5google.com/2026/05/19/google-io-2026-news/
3•gmays•1h ago•1 comments

Cross-Model Context Inheritance in Anthropic's Claude: 94 Days of Non-Response

https://github.com/AIM-Nelson/cross-model-context-inheritance
1•Malinor•1h ago•0 comments

Knex Mechanical Computer (MechaDigit-1) [video]

https://www.youtube.com/watch?v=PAWZ2Zjsah0
1•Teever•1h ago•0 comments