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

I tried Karpathy's Autoresearch on an old research project

https://ykumar.me/blog/eclip-autoresearch/
67•ykumards•57m ago•13 comments

iPhone 17 Pro Demonstrated Running a 400B LLM

https://twitter.com/anemll/status/2035901335984611412
319•anemll•5h ago•186 comments

Trivy under attack again: Widespread GitHub Actions tag compromise secrets

https://socket.dev/blog/trivy-under-attack-again-github-actions-compromise
88•jicea•1d ago•31 comments

Local Stack Archived their GitHub repo and requires an account to run

https://github.com/localstack/localstack
20•ecshafer•41m ago•3 comments

The quadratic problem nobody fixed

https://iev.ee/blog/the-quadratic-problem-nobody-fixed/
32•lalitmaganti•4d ago•5 comments

US govt pays TotalEnergies nearly $1B to stop US offshore wind projects

https://www.lemonde.fr/en/international/article/2026/03/23/us-and-totalenergies-reach-nearly-1-bi...
138•lode•2h ago•62 comments

BIO: The Bao I/O Coprocessor

https://www.bunniestudios.com/blog/2026/bio-the-bao-i-o-coprocessor/
58•zdw•3d ago•18 comments

Cyber.mil serving file downloads using TLS certificate which expired 3 days ago

https://www.cyber.mil/stigs/downloads
123•Eduard•4h ago•113 comments

Digs: Offline-first iOS app to browse your Discogs vinyl collection

https://lustin.fr/blog/building-digs/
19•rlustin•10h ago•5 comments

Bombadil: Property-based testing for web UIs

https://github.com/antithesishq/bombadil
194•Klaster_1•4d ago•76 comments

An unsolicited guide to being a researcher [pdf]

https://emerge-lab.github.io/papers/an-unsolicited-guide-to-good-research.pdf
126•sebg•4d ago•19 comments

I built an AI receptionist for a mechanic shop

https://www.itsthatlady.dev/blog/building-an-ai-receptionist-for-my-brother/
133•mooreds•9h ago•150 comments

Two pilots dead after plane and ground vehicle collide at LaGuardia

https://www.bbc.com/news/articles/cy01g522ww4o
182•mememememememo•12h ago•311 comments

Show HN: Threadprocs – executables sharing one address space (0-copy pointers)

https://github.com/jer-irl/threadprocs
45•jer-irl•3h ago•33 comments

Migrating to the EU

https://rz01.org/eu-migration/
726•exitnode•9h ago•572 comments

Is it a pint?

https://isitapint.com/
129•cainxinth•3h ago•117 comments

Walmart: ChatGPT checkout converted 3x worse than website

https://searchengineland.com/walmart-chatgpt-checkout-converted-worse-472071
330•speckx•3d ago•228 comments

PC Gamer recommends RSS readers in a 37mb article that just keeps downloading

https://stuartbreckenridge.net/2026-03-19-pc-gamer-recommends-rss-readers-in-a-37mb-article/
785•JumpCrisscross•1d ago•359 comments

Anchor: Hardware-based authentication using SanDisk USB devices

4•rewant•4d ago•1 comments

If DSPy is so great, why isn't anyone using it?

https://skylarbpayne.com/posts/dspy-engineering-patterns/
170•sbpayne•4h ago•104 comments

GitHub appears to be struggling with measly three nines availability

https://www.theregister.com/2026/02/10/github_outages/
377•richtr•8h ago•194 comments

General Motors is assisting with the restoration of a rare EV1

https://evinfo.net/2026/03/general-motors-is-assisting-with-the-restoration-of-an-1996-ev1/
72•betacollector64•3d ago•84 comments

Side-Effectful Expressions in C (2023)

https://blog.xoria.org/expr-stmt-c/
23•surprisetalk•5d ago•1 comments

The gold standard of optimization: A look under the hood of RollerCoaster Tycoon

https://larstofus.com/2026/03/22/the-gold-standard-of-optimization-a-look-under-the-hood-of-rolle...
536•mariuz•1d ago•149 comments

“Collaboration” is bullshit

https://www.joanwestenberg.com/collaboration-is-bullshit/
194•mitchbob•17h ago•94 comments

Reports of code's death are greatly exaggerated

https://stevekrouse.com/precision
553•stevekrouse•1d ago•410 comments

Tin Can, a 'landline' for kids

https://www.businessinsider.com/tin-can-landline-kids-cellphone-cell-alternative-how-2025-9
286•tejohnso•3d ago•231 comments

The future of version control

https://bramcohen.com/p/manyana
633•c17r•1d ago•356 comments

Show HN: The King Wen Permutation: [52, 10, 2]

https://gzw1987-bit.github.io/iching-math/
51•gezhengwen•11h ago•24 comments

Can you get root with only a cigarette lighter? (2024)

https://www.da.vidbuchanan.co.uk/blog/dram-emfi.html
159•HeliumHydride•3d ago•31 comments