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

CERN uses tiny AI models burned into silicon for real-time LHC data filtering

https://theopenreader.org/Journalism:CERN_Uses_Tiny_AI_Models_Burned_into_Silicon_for_Real-Time_L...
68•TORcicada•2h ago•48 comments

Go hard on agents, not on your filesystem

https://jai.scs.stanford.edu/
357•mazieres•9h ago•201 comments

AMD's Ryzen 9 9950X3D2 Dual Edition crams 208MB of cache into a single chip

https://arstechnica.com/gadgets/2026/03/amds-ryzen-9-9950x3d2-dual-edition-crams-208mb-of-cache-i...
170•zdw•8h ago•91 comments

Matadisco – Decentralized Data Discovery

https://matadisco.org/
10•biggestfan•2d ago•1 comments

Make macOS consistently bad unironically

https://lr0.org/blog/p/macos/
418•speckx•15h ago•296 comments

The bee that everyone wants to save

https://naturalist.bearblog.dev/the-bee-that-everyone-wants-to-save/
110•nivethan•2d ago•27 comments

Trust Signals as Sparklines for Hacker News

https://hn-trustspark.com/
42•solaire_oa•1d ago•18 comments

LG's new 1Hz display is the secret behind a new laptop's battery life

https://www.pcworld.com/article/3096432/lgs-new-1hz-display-is-the-secret-behind-a-new-laptops-ba...
246•robotnikman•4d ago•112 comments

Anatomy of the .claude/ folder

https://blog.dailydoseofds.com/p/anatomy-of-the-claude-folder
487•freedomben•20h ago•224 comments

Show HN: Twitch Roulette – Find live streamers who need views the most

https://twitchroulette.net/
126•ellg•12h ago•61 comments

.apks are just .zips; semi-legally hacking software for orphaned hardware [video]

https://www.youtube.com/watch?v=P1kfuCkWo24
49•abadar•2d ago•35 comments

Nashville library launches Memory Lab for digitizing home movies

https://www.axios.com/local/nashville/2026/03/16/nashville-library-digitize-home-movies
151•toomuchtodo•4d ago•37 comments

Desperately Seeking Space Friends

https://reviewcanada.ca/magazine/2026/04/desperately-seeking-space-friends-review-the-pale-blue-d...
9•benbreen•2d ago•0 comments

Velxio 2.0 – Emulate Arduino, ESP32, and Raspberry Pi 3 in the Browser

https://github.com/davidmonterocrespo24/velxio
150•dmcrespo•13h ago•44 comments

ISBN Visualization

https://annas-archive.gd/isbn-visualization?
171•Cider9986•14h ago•28 comments

‘Energy independence feels practical’: Europeans building mini solar farms

https://www.euronews.com/2026/03/26/suddenly-energy-independence-feels-practical-europeans-are-bu...
289•vrganj•1d ago•270 comments

Arm releases first in-house chip, with Meta as debut customer

https://www.cnbc.com/2026/03/24/arm-launches-its-own-cpu-with-meta-as-first-customer.html
16•goplayoutside•3d ago•5 comments

Meow.camera

https://meow.camera/#4258783365322591678
278•surprisetalk•19h ago•63 comments

Go Naming Conventions: A Practical Guide

https://www.alexedwards.net/blog/go-naming-conventions
3•yurivish•3d ago•0 comments

Iran-linked hackers breach FBI director's personal email

https://www.reuters.com/world/us/iran-linked-hackers-claim-breach-of-fbi-directors-personal-email...
259•m-hodges•19h ago•380 comments

Installing a Let's Encrypt TLS certificate on a Brother printer with Certbot

https://owltec.ca/Other/Installing+a+Let%27s+Encrypt+TLS+certificate+on+a+Brother+printer+automat...
216•8organicbits•20h ago•52 comments

Explore the Hidden World of Sand

https://magnifiedsand.com/
238•RAAx707•4d ago•39 comments

The Future of SCIP

https://sourcegraph.com/blog/the-future-of-scip
74•jdorfman•18h ago•22 comments

Telnyx package compromised on PyPI

https://telnyx.com/resources/telnyx-python-sdk-supply-chain-security-notice-march-2026
104•ramimac•1d ago•107 comments

Improving Composer through real-time RL

https://cursor.com/blog/real-time-rl-for-composer
81•ingve•1d ago•24 comments

Building FireStriker: Making Civic Tech Free

https://firestriker.org/blog/building-firestriker-why-im-making-civic-tech-free
126•noleary•1d ago•26 comments

People inside Microsoft are fighting to drop mandatory Microsoft Account

https://www.windowscentral.com/microsoft/windows-11/people-inside-microsoft-are-fighting-to-drop-...
650•breve•20h ago•497 comments

Ask HN: Founders of estonian e-businesses – is it worth it?

131•udl•4d ago•71 comments

Fets and Crosses: Tic-Tac-Toe built from 2458 discrete transistors

https://schilk.co/projects/fetsncrosses/
49•voxadam•3d ago•12 comments

Desk for people who work at home with a cat

https://soranews24.com/2026/03/27/japan-now-has-a-special-desk-for-people-who-work-at-home-with-a...
416•zdw•19h ago•150 comments