frontpage.
newsnewestaskshowjobs

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();
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";
  }
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.

LLMs won't break symmetric crypto

https://www.bfswa.blog/p/llms-wont-break-symmetric-crypto
34•rowbin•1h ago•19 comments

Nashville uses eminent domain to block data center near zoo

https://www.costar.com/article/970809918/nashville-council-approves-eminent-domain-action-to-halt...
17•mapping365•42m ago•1 comments

Discovery Loop

https://www.discoveryloop.com/
622•xtreak29•10h ago•392 comments

Zed DeltaDB

https://zed.dev/deltadb
324•ahamez•8h ago•166 comments

The title cards in Blade Runner are amazing

https://randsinrepose.com/archives/blade-runner-title-cards/
165•ExMachina73•5h ago•72 comments

Changes at Google DeepMind: Demis Hassabis from CEO to Chair, Jeff Dean departs

https://blog.google/company-news/inside-google/message-ceo/next-chapter-ai-momentum/
503•colesantiago•10h ago•609 comments

Muse Code and Muse Spark 1.2

https://research.meta.ai/blog/introducing-muse-code-and-muse-spark-1-2
192•paulkrush•7h ago•112 comments

Beating GPT-5.6 Sol on retrieval with 100x cheaper open models

https://neon.com/blog/how-castform-neon-beats-frontier-models-on-price-and-efficiency
233•moonikakiss•8h ago•57 comments

Prime Agent: A self-improving RLM agent

https://www.primeintellect.ai/blog/prime-agent
112•Xeophon•5h ago•20 comments

Born Against, or why hobby programming communities are against LLM usage

https://blog.fogus.me/llm/born-against.html
153•lladnar•8h ago•152 comments

Branchless Rust: Making a Filter 4x Faster by Removing an If

https://www.greyblake.com/blog/branchless-rust/
35•greyblake•2d ago•3 comments

Atlassian Rovo Exfiltrates Data, Bypassing Controls

https://www.promptarmor.com/resources/atlassian-rovo-exfiltrates-data
180•hackerBanana•9h ago•71 comments

NVIDIA’s Vera Whitepaper Has a Thread Loose

https://chipsandcheese.com/p/nvidias-vera-whitepaper-has-a-thread
93•pella•5h ago•13 comments

Cloudflare OS: an open platform for agents, apps, and work

https://blog.cloudflare.com/cloudflare-os/
482•speckx•12h ago•244 comments

Something is changing in the unit economics of software

https://nicolo.xyz/something-is-changing-in-the-unit-economics-of-software/
38•coconido•10h ago•25 comments

I'll be stepping back from leading product for X

https://twitter.com/nikitabier/status/2085105586966827343/
76•DearAll•5h ago•110 comments

I'm switching my phone from Android to Linux

https://runarcn.no/android-to-linux/
230•speckx•7h ago•187 comments

GNU Hurd News 2026-Q2

https://www.gnu.org/software/hurd/news/2026-q2.html
134•plaguna•3d ago•93 comments

Celld: Self-hosted, distributed Durable Objects

https://github.com/denoland/celld
156•calvinfo•10h ago•30 comments

Exact, parallel 2D Delaunay triangulation for int32 coordinates

https://github.com/morishuz/delaunay32
33•oryx1729•5d ago•2 comments

Pushing the limits of RISC-V emulation

https://shuklaayu.sh/blog/riscv-recompiler
29•shuklaayush•1w ago•10 comments

Position: LLMs Can't Jump

https://openreview.net/challenge?redirect=%2Fforum%3Fid%3DklU4737opt
247•theanonymousone•15h ago•170 comments

New Keyboard: Alicja v2

https://marcin.juszkiewicz.com.pl/2026/07/29/new-keyboard-alicja-v2/
3•jandeboevrie•6d ago•0 comments

Goodhart's Law Comes for Every Benchmark You Trust

https://cacm.acm.org/blogcacm/goodharts-law-comes-for-every-benchmark-you-trust/
67•pseudolus•5d ago•31 comments

The Origins of Vintage Comics Part 1

https://www.truegrittexturesupply.com/blogs/news/origins-of-the-vintage-comics-aesthetic-part-1
12•Michelangelo11•6d ago•1 comments

Sycophantic AI Decreases Prosocial Intentions and Promotes Dependence (2025)

https://arxiv.org/abs/2510.01395
80•robin_reala•8h ago•56 comments

Discovery of a multicomponent alloy forged by the Hiroshima atomic blast

https://www.science.org/doi/10.1126/sciadv.aeg8299
111•_____k•6d ago•52 comments

Launch HN: HyperProbe (YC S26) – Agents that do read-only debugging in prod

https://www.hyperprobe.co
45•shailendraht•10h ago•32 comments

Online Friends Are Real Friends

https://toska.bearblog.dev/re-online-friends-are-real-friends/
73•Tomte•5d ago•49 comments

The Entropy of a Markov Chain

https://chillphysicsenjoyer.substack.com/p/the-entropy-of-a-markov-chain
107•surprisetalk•12h ago•9 comments