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.

RequestRocket Promo Key

https://requestrocket.com
1•geoicons•9m ago•1 comments

Doop

https://doop.design/
1•handfuloflight•12m ago•0 comments

Im In

1•domainsearchkin•13m ago•0 comments

What Happened to the TI-83? Sold to Every Student in 1996 Then Destroyed Itself

https://www.youtube.com/watch?v=X9YqHX0Twg4
1•cable2600•17m ago•0 comments

RustDrop – privacy-first P2P file transfer for your LAN (Rust)

https://github.com/hakuxyz/rustdrop
1•xyzhaku•18m ago•0 comments

How AI may drive union-resistant tech workers to the bargaining table

https://www.theguardian.com/technology/2026/jul/21/ai-tech-workers-unionize
1•civilchaos•19m ago•0 comments

Avoid Public Functions Calling Other Public Functions

https://matklad.github.io/2026/10/29/pub-calls-pub.html
3•birdculture•24m ago•0 comments

Wikimedia Foundation amicus brief regarding OpenAI [pdf]

https://commons.wikimedia.org/w/index.php?title=File%3A26.10.29_WMF_motion_and_amicus_In_re_OAI.p...
1•gnabgib•26m ago•0 comments

Amazon made the AUX input on older Alexa devices less useful

https://www.engadget.com/2300219/amazon-made-alexa-devices-aux-port-less-useful/
3•NordStreamYacht•27m ago•0 comments

The Elephant-Goldfish Model plugin for spec-driven AI development

https://opensource.googleblog.com/2026/10/introducing-elephant-goldfish-model-plugin.html
1•derekleeth•28m ago•0 comments

Show HN: Vela, a New Linux Desktop Environment

https://velade.org/blog/vela-0-1/
3•BrandoDev_it•32m ago•0 comments

Bashttpd: A web server written in bash

https://github.com/avleen/bashttpd
1•denysonique•34m ago•0 comments

Wikimedia Foundation Tries to Save Itself by Brokering AI Copyright Deal

https://gizmodo.com/wikimedia-foundation-tries-to-save-itself-from-oblivion-by-brokering-ai-copyr...
4•CharlesW•37m ago•0 comments

Tell HN: ChatGPT and Codex usage will be combined

4•FergusArgyll•40m ago•2 comments

Analysts find looming launch crisis is "more severe" than anticipated

https://arstechnica.com/space/2026/10/analysts-find-looming-launch-crisis-is-more-severe-than-ant...
1•rbanffy•43m ago•0 comments

Toit v2.0.0

https://toit.io/blog/toit-v2-0-0/
2•floitsch•43m ago•0 comments

Docsferatu: An agent that drafts docs PRs while you sleep

https://www.inngest.com/blog/docsferatu-an-agent-that-drafts-docs-prs-while-you-sleep
1•Linell•44m ago•0 comments

Treatments for age-related infertility are being developed at last

https://www.economist.com/science-and-technology/2026/10/26/treatments-for-age-related-infertilit...
2•Anon84•48m ago•0 comments

Supersonic airliner in doubt as company shifts to powering AI data centers

https://arstechnica.com/gadgets/2026/10/united-airlines-ceo-doubts-supersonic-airliner-from-boom-...
1•rbanffy•49m ago•0 comments

Show HN: Bobby – Over Engineering PR Reviews

https://bobby.viraj.computer/
1•angrybayblade•52m ago•0 comments

Show HN: BBRouter – Ben Eater's 8-bit computer, simulated on 3D breadboards

https://bbrouter.com/bbrouter/ben-eater-sap-1
3•creack•57m ago•0 comments

Donnie Darko: A Mind-Twisting Cult Classic Turns 25

https://www.nytimes.com/2026/10/26/movies/donnie-darko-oral-history-25-year-anniversary.html
4•gnabgib•1h ago•1 comments

Honest Government Ad – AI Data Centres [video]

https://www.youtube.com/watch?v=kON2ZI2BNj8
2•SockThief•1h ago•0 comments

Honest Government Ad – The Great FuckOffening [video]

https://www.youtube.com/watch?v=v_Lua2Xzg5s
1•SockThief•1h ago•0 comments

Aesthetic City Builder

https://game.theaestheticcity.com
3•idbnstra•1h ago•0 comments

Smear Campaign Towards GrapheneOS

https://grapheneos.social/@GrapheneOS/117537776055163844
7•monneyboi•1h ago•1 comments

Chainalysis security incident with customers PII compromised

https://www.chainalysis.com/blog/security-incident-october-30/
4•androidnstuff•1h ago•0 comments

Constructing a Quine from Kleene's Second Recursion Theorem

https://emarzion.github.io/KSRT/
1•mkckto•1h ago•0 comments

Frontiers – Association between statin therapy and dementia risk

https://www.frontiersin.org/journals/pharmacology/articles/10.3389/fphar.2026.1915633/full
1•bilsbie•1h ago•0 comments

A collection of custom M-VAVE FM1 Firmware

https://fm1-editor.com/firmware/
1•natebc•1h ago•0 comments