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

Comments

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

We Will Not Be Divided

https://notdivided.org
1508•BloondAndDoom•7h ago•505 comments

How do I cancel my ChatGPT subscription?

https://help.openai.com/en/articles/7232927-how-do-i-cancel-my-chatgpt-subscription
668•tobr•2h ago•167 comments

Croatia declared free of landmines after 31 years

https://glashrvatske.hrt.hr/en/domestic/croatia-declared-free-of-landmines-after-31-years-12593533
223•toomuchtodo•6h ago•37 comments

Don't use passkeys for encrypting user data

https://blog.timcappalli.me/p/passkeys-prf-warning/
138•zdw•5h ago•77 comments

Rust Is Just a Tool

https://lewiscampbell.tech/blog/260204.html
66•JuniperMesos•3h ago•41 comments

Cash issuing terminals

https://computer.rip/2026-02-27-ibm-atm.html
54•zdw•3h ago•2 comments

OpenAI agrees with Dept. of War to deploy models in their classified network

https://twitter.com/sama/status/2027578652477821175
573•eoskx•5h ago•292 comments

Show HN: I ported Manim to TypeScript (run 3b1B math animations in the browser)

https://github.com/maloyan/manim-web
95•maloyan•2d ago•13 comments

A new California law says all operating systems need to have age verification

https://www.pcgamer.com/software/operating-systems/a-new-california-law-says-all-operating-system...
567•WalterSobchak•17h ago•523 comments

OpenAI raises $110B on $730B pre-money valuation

https://techcrunch.com/2026/02/27/openai-raises-110b-in-one-of-the-largest-private-funding-rounds...
479•zlatkov•17h ago•522 comments

Smallest transformer that can add two 10-digit numbers

https://github.com/anadim/AdderBoard
147•ks2048•1d ago•65 comments

Statement on the comments from Secretary of War Pete Hegseth

https://www.anthropic.com/news/statement-comments-secretary-war
885•surprisetalk•7h ago•298 comments

U.S. and Israel Conduct Strikes on Iran

https://www.nytimes.com/live/2026/02/28/world/iran-strikes-trump
212•gammarator•1h ago•159 comments

Qt45: A small polymerase ribozyme that can synthesize itself

https://www.science.org/doi/10.1126/science.adt2760
79•ppnpm•9h ago•15 comments

Bootc and OSTree: Modernizing Linux System Deployment

https://a-cup-of.coffee/blog/ostree-bootc/
33•mrtedbear•5h ago•3 comments

A better streams API is possible for JavaScript

https://blog.cloudflare.com/a-better-web-streams-api/
405•nnx•18h ago•139 comments

A Chinese official’s use of ChatGPT revealed an intimidation operation

https://www.cnn.com/2026/02/25/politics/chatgpt-china-intimidation-operation
203•cwwc•17h ago•122 comments

The Eternal Promise: A History of Attempts to Eliminate Programmers

https://www.ivanturkovic.com/2026/01/22/history-software-simplification-cobol-ai-hype/
10•dinvlad•3d ago•1 comments

Inferring Car Movement Patterns from Passive TPMS Measurements

https://dspace.networks.imdea.org/handle/20.500.12761/2011
7•wisdomseaker•1h ago•1 comments

NASA announces overhaul of Artemis program amid safety concerns, delays

https://www.cbsnews.com/news/nasa-artemis-moon-program-overhaul/
251•voxadam•16h ago•272 comments

Package Managers à la Carte: a formal model of dependency resolution

https://arxiv.org/abs/2602.18602
24•avsm•3d ago•5 comments

5,300-year-old 'bow drill' rewrites story of ancient Egyptian tools

https://phys.org/news/2026-02-year-drill-rewrites-story-ancient.html
9•PaulHoule•2d ago•0 comments

Eschewing Zshell for Emacs Shell (2014)

https://www.howardism.org/Technical/Emacs/eshell-fun.html
29•pvdebbe•3d ago•12 comments

Open source calculator firmware DB48X forbids CA/CO use due to age verification

https://github.com/c3d/db48x/commit/7819972b641ac808d46c54d3f5d1df70d706d286
173•iamnothere•17h ago•88 comments

Time-Travel Debugging: Replaying Production Bugs Locally

https://lackofimagination.org/2026/02/time-travel-debugging-replaying-production-bugs-locally/
17•tie-in•2d ago•2 comments

Show HN: Claude-File-Recovery, recover files from your ~/.claude sessions

https://github.com/hjtenklooster/claude-file-recovery
79•rikk3rt•16h ago•30 comments

Inventing the Lisa user interface – Interactions

https://dl.acm.org/doi/10.1145/242388.242405
35•rbanffy•2d ago•2 comments

Show HN: Unfucked - version all changes (by any tool) - local-first/source avail

https://www.unfudged.io/
96•cyrusradfar•1d ago•53 comments

Let's discuss sandbox isolation

https://www.shayon.dev/post/2026/52/lets-discuss-sandbox-isolation/
139•shayonj•14h ago•44 comments

Can you reverse engineer our neural network?

https://blog.janestreet.com/can-you-reverse-engineer-our-neural-network/
289•jsomers•3d ago•186 comments