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

Plowshares or nuclear explosions for the national economy

https://annasofialesiv.substack.com/p/plowshares
1•bilsbie•1m ago•0 comments

Stop Doing Easy Things

https://xendo.bearblog.dev/stop-doing-easy-things/
1•xendo•2m ago•0 comments

The Universe is a Sheet of Paper (and Some Sand)

https://t3db0t.substack.com/p/the-universe-is-a-sheet-of-paper
2•virgil_disgr4ce•4m ago•0 comments

DeepSWE: A contamination-free benchmark for long-horizon coding agents

https://deepswe.datacurve.ai/blog
2•ammar_x•4m ago•1 comments

DeepSWE Benchmark

https://deepswe.datacurve.ai/
1•xfax•7m ago•0 comments

Hedge Funds Are AImaxxing

https://www.ft.com/content/66fc88ec-af0d-452f-a535-193d9d5279f8
1•johnbarron•7m ago•0 comments

Fifty Years of Transaction Processing Research

https://arxiv.org/abs/2605.20466
1•qianli_cs•8m ago•0 comments

Vibe Coding Escapades: pelican-copy-code plugin

https://blog.fidelramos.net/software/vibe-coding-escapades-pelican-copy-code
3•tripu•9m ago•0 comments

Does a trusted AI asset marketplace solve this issue?

https://kimura.yumiwillems.com/p/why-ais-biggest-deals-price-assets
2•BehaviorGraph•9m ago•0 comments

Consumer Founders

https://2lr.substack.com/p/consumer-founders-building-the-impossible
1•jdenquin•9m ago•0 comments

R vs. Dudley and Stephens

https://en.wikipedia.org/wiki/R_v_Dudley_and_Stephens
1•benbreen•11m ago•0 comments

How we contain Claude across products

https://www.anthropic.com/engineering/how-we-contain-claude
2•siegers•12m ago•0 comments

AI chatbots show bias toward Catholicism, researchers say

https://decrypt.co/369045/ai-chatbots-claude-chatgpt-bias-catholicism-pope-leo
5•pseudosim•12m ago•2 comments

Tokens Never Die

https://artsabintsev.substack.com/p/tokens-never-die
1•Arts86•13m ago•0 comments

Laguna M.1/XS.2 Technical Report [pdf]

https://poolside.ai/assets/laguna/laguna-m1-xs2-technical-report.pdf
1•rexledesma•13m ago•0 comments

Show HN: Clipmon – Menubar Clipboard Manager for macOS

https://github.com/C9-Labs/clipmon
2•vednig•15m ago•0 comments

Top Sanity Agencies to Hire in 2026

https://gitnation.com/contents/12-top-sanity-cms-development-agencies-to-hire
1•katyadrozd•17m ago•0 comments

Google ADK now available for Kotlin

https://developers.googleblog.com/adk-kotlin-android-building-ai-agents/
1•avanwyk•17m ago•0 comments

Genshin Impact company miHoYo keeps stealing from indie games

https://bsky.app/profile/michaelkamm.games/post/3mmrfwqupos2s
2•sourencho•18m ago•0 comments

LMIM OS – an offline AI ecosystem. Voice, RAG, WhatsApp. ++ One file. 0 setup

https://lmim.tech
1•iamonthemission•18m ago•0 comments

John Carmack on Inlined Code

http://number-none.com/blow/john_carmack_on_inlined_code.html
1•tosh•18m ago•0 comments

Deploying Rust to Production Checklist

https://kerkour.com/rust-production-checklist
1•aniviacat•19m ago•0 comments

NPR maintains the most complete database and visual archive of J6 prosecutions

https://apps.npr.org/jan-6-archive/
7•rolph•20m ago•0 comments

Chemistry behind the Garden Grove chemical tank

https://www.science.org/content/blog-post/methyl-methacrylate-tank
4•nooks•20m ago•0 comments

The Melancholy of Slaying Monsters

https://thereader.mitpress.mit.edu/the-strange-melancholy-of-slaying-monsters/
2•prismatic•20m ago•0 comments

Your Stack Overflow Graphs Prove Nothing

https://techstackups.com/articles/stackoverflow-graphs-prove-nothing/
1•sixhobbits•21m ago•0 comments

Show HN: CredWork – a simple project tracking and showcasing tool

https://www.credwork.co/
1•tusharcw•22m ago•0 comments

Visibility into the Black Box

https://matgreten.dev/posts/visibility-into-the-black-box/
1•nickstinemates•22m ago•0 comments

False Positive OSV Advisories Reported by Amazon Inspector

https://github.com/ossf/malicious-packages/pull/1276/files
1•joeyhage•22m ago•1 comments

Software After Software

https://twitter.com/thorstenball/status/2059304318055150066
1•tosh•23m ago•0 comments