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.

John Carmack on the mistakes around Quake that ruined id software

https://twitter.com/ID_AA_Carmack/status/2069799283369345247
198•shadowtree•1h ago•78 comments

RubyLLM: A Ruby framework for all major AI providers

https://rubyllm.com/
170•doener•2h ago•22 comments

We’re making Bunny DNS free

https://bunny.net/blog/were-making-bunny-dns-free/
634•dabinat•8h ago•210 comments

CAPTCHAs have failed for 20 years

https://www.browserbase.com/blog/why-captchas-are-getting-harder
27•harsehaj•1h ago•19 comments

Show HN: Nub – A Bun-like all-in-one toolkit for Node.js

https://github.com/nubjs/nub
105•colinmcd•2h ago•23 comments

I taught a bucket to speak Git

https://www.tigrisdata.com/blog/objgit/
21•xena•1h ago•2 comments

PR spam today looks like email spam in the early 2000s

https://www.greptile.com/blog/prs-on-openclaw
30•dakshgupta•2h ago•19 comments

For Most of the World, Open-Source AI Is the Only Way Forward

https://techstrong.ai/articles/for-most-of-the-world-open-source-ai-is-the-only-way-forward/
37•CrankyBear•2h ago•3 comments

Running Windows Games on a Hobby OS with Wine

https://astral-os.org/posts/2026/04/03/wine-on-astral.html
44•avaliosdev•2h ago•11 comments

Krea 2: SOTA open-weights 12B image model

https://www.krea.ai/blog/krea-2-technical-report
166•mattnewton•1d ago•21 comments

A Practical Guide to SSH Tunnels: Local and Remote Port Forwarding

https://labs.iximiuz.com/tutorials/ssh-tunnels
152•signa11•4d ago•30 comments

Genuinely, my all-time favourite image: Mamenchisaurus hochuanensis

https://svpow.com/2026/06/04/genuinely-my-all-time-favourite-image-mamenchisaurus-hochuanensis/
41•surprisetalk•2d ago•11 comments

Boffin claims Microsoft's "quantum leap" is invalid due to "basic Python errors"

https://www.theregister.com/research/2026/06/24/boffin-claims-microsofts-supposed-quantum-leap-do...
63•connorboyle•1h ago•28 comments

Show HN: Monolisa v3 – a typeface for developers and creatives

https://www.monolisa.dev/
85•bebraw•2d ago•18 comments

Haystack: Open-Source AI Framework for Production Ready Agents, RAG

https://haystack.deepset.ai/
60•doener•5h ago•19 comments

Founding a company in Germany: €9600, 152 days and I still can't send an invoice

https://paolino.me/founding-a-company-in-germany/
430•earcar•4h ago•494 comments

Show HN: Pure Effect – Reproduce production bugs on your laptop without a DB

https://pure-effect.org
30•tie-in•2d ago•6 comments

Stealing Is a Skill

https://ben-mini.com/2026/stealing-is-a-skill
109•bewal416•3h ago•76 comments

Edsger Dijkstra's Library (Housed and Archived in Leuven, Belgium)

https://www.dijkstrascry.com/inventory
19•rramadass•1h ago•2 comments

Raspberry Pi Pico W as USB Wi-Fi Adapter

https://gitlab.com/baiyibai/pico-usb-wifi
229•byb•13h ago•108 comments

Systems optimization should be part of CI/CD

https://ucbskyadrs.github.io/blog/levi/
19•ttanv•4h ago•2 comments

Statistics that live in your SQL

https://kolistat.com/blog/the-stats-duck-v0-6-0/
111•caerbannogwhite•2d ago•15 comments

OpenAI and Broadcom unveil LLM-optimized inference chip

https://openai.com/index/openai-broadcom-jalapeno-inference-chip/
111•meetpateltech•3h ago•36 comments

Ashby (YC W19) Is Hiring EMEA Engineers Who Can Design

https://www.ashbyhq.com/careers?ashby_jid=87b96eef-edc1-4de4-adb6-d460126d02f8&utm_source=hn
1•abhikp•10h ago

Quebec town recognizes trees as living beings with rights

https://www.cbc.ca/news/canada/montreal/terrasse-vaudreil-quebec-tree-rights-9.7243634
65•speckx•1h ago•57 comments

"Fix" MacBook Neo Cursor Lag: Record 1 Pixel of the Screen Every 10 Seconds

https://gist.github.com/retroplasma/ec21767d0a8380c7ea9c2fbee1c7d6bf
190•retroplasma•14h ago•78 comments

François Englert (1932 – 2026)

https://home.cern/francois-englert-1932-2026/
51•toomuchtodo•3d ago•3 comments

Too many R packages: CRAN is inundated with submissions

https://rworks.dev/posts/too-many-R-packages/
74•ionychal•6h ago•58 comments

Show HN: peerd – AI agent harness that runs entirely in your browser

https://github.com/NotASithLord/peerd
9•NotASithLord•1d ago•2 comments

Minimus container images are now free

https://images.minimus.io/
100•dimastopel•5h ago•59 comments