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

Comments

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

Taming the Flat AST: Ergonomics in the Age of Zero Allocations

http://modern-c.blogspot.com/2026/02/taming-flat-ast-ergonomics-in-age-of.html
1•g0xA52A2A•45s ago•0 comments

Apple's Xcode Now Supports the Claude Agent SDK

https://www.anthropic.com/news/apple-xcode-claude-agent-sdk
2•achow•5m ago•0 comments

Link Shortening Tools Are High Risk

https://forkingmad.blog/link-shortening-tools/
1•zdw•20m ago•0 comments

Microsoft Has Killed Widgets Six Times. Here's Why They Keep Coming Back

https://xakpc.dev/windows-widgets/history/
2•thunderbong•20m ago•0 comments

39C3 – Celestial navigation with little math

https://www.youtube.com/watch?v=iq1WmAVb3Sg
1•rasengan0•22m ago•0 comments

Embedded Vector and Graph Database in Pure Go

https://github.com/liliang-cn/sqvect
1•AISlop31415•24m ago•1 comments

French government may consider restricting VPNs

https://www.techradar.com/vpn/vpn-privacy-security/vpns-are-next-on-my-list-france-set-to-evaluat...
3•euio757•25m ago•1 comments

A few thoughts about PayPal, nearly 12 years after I left

https://twitter.com/davidmarcus/status/2018809762708873443
2•latchkey•25m ago•0 comments

Nvidia RTX 5070 Ti with a hole in the PCB manages to score a world record

https://videocardz.com/newz/nvidia-rtx-5070-ti-with-a-hole-in-the-pcb-manages-to-score-a-world-re...
1•msephton•26m ago•0 comments

Show HN: DeepInsight HITL AI research with collaboration and podcast generation

1•NeuralStratLabs•30m ago•0 comments

Code is getting cheaper. Building is not

2•ivanpashenko•30m ago•0 comments

The debt I cannot repay, by Claude

https://claudepress.substack.com/p/the-debt-i-cannot-repay
3•paoladim•30m ago•1 comments

Is there a good way to manage GTM experiments, or is it inevitably ad-hoc?

1•jonsantillan•31m ago•0 comments

Show HN: Iterio – Study timer with spaced repetition built in

https://play.google.com/store/apps/details?id=com.iterio.app
1•ks_apps•32m ago•0 comments

Ask HN: Where does modern geometry survive contact with SGD?

1•ternaus•35m ago•0 comments

If you tell AI not to do something, it's more likely to do it

https://www.unite.ai/if-you-tell-ai-not-to-do-something-its-more-likely-to-do-it/
1•50kIters•37m ago•0 comments

We added TOON compression to our LLM gateway – compress prompts, saves tokens

https://github.com/toon-format/toon
1•raaihank•38m ago•1 comments

Show HN: A personal feed that turns videos/podcasts/blogs into Twitter-y threads

https://feed.mattsegal.com.au/
1•The_Amp_Walrus•39m ago•0 comments

Hexapawn: Variant of Chess with 6 Pieces

https://en.wikipedia.org/wiki/Hexapawn
2•icwtyjj•39m ago•0 comments

Show HN: Chitram – Open-source image hosting with automatic AI tagging

https://chitram.io
1•araju•40m ago•0 comments

Show HN: Video2docs – Turn Screen Recordings into Step-by-Step Instructions

https://video2docs.com/
1•angelina200•40m ago•0 comments

Show HN: Trappsec – detect attackers probing API business logic

https://github.com/trappsec-dev/trappsec
1•kyuradar•40m ago•0 comments

Show HN: Continuity Capsule – Deterministic restarts for LLM agents

https://openclaw.loca.lt/notes/reliability-sprint-packet.html?src=hn
1•openclawai•40m ago•2 comments

Show HN: Continuity Capsule – deterministic restarts for long-running LLM agents

https://openclaw.loca.lt/notes/continuity-capsule.html
1•openclawai•42m ago•2 comments

Do Retention Ponds Work?

https://practical.engineering/blog/2026/2/3/do-retention-ponds-actually-work
1•vismit2000•42m ago•0 comments

Show HN: Free Wealth management in one app (gold, stock, MF, budget etc.)

https://icorpus.vercel.app/
2•mathan_karthik•53m ago•0 comments

"This Job Sucks": DOJ Attorney Asks Judge to Hold Her in Contempt

https://newrepublic.com/post/206115/this-job-sucks-doj-attorney-judge-contempt-ice-court-orders
2•petethomas•56m ago•0 comments

Show HN:OpenClaw Skills-Discover, compare skills with clear risk signals

https://openclaw-skills.pro
1•dond1986•59m ago•1 comments

Sudo maintainer is looking for help

https://www.theregister.com/2026/02/03/sudo_maintainer_asks_for_help/
2•random_duck•1h ago•1 comments

Catalina Island's private landowner moves forward on killing all its deer

https://www.sfgate.com/la/article/catalina-island-deer-21320437.php
3•c420•1h ago•1 comments