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

Mathematical methods and human thought in the age of AI

https://arxiv.org/abs/2603.26524
66•zaikunzhang•2h ago•6 comments

Ghostmoon.app – The Swiss Army Knife for your macOS menu bar

https://www.mgrunwald.com/ghostmoon/
82•mgrunwald_•2h ago•75 comments

The curious case of retro demo scene graphics

https://www.datagubbe.se/aipixels/
254•zdw•8h ago•60 comments

I use excalidraw to manage my diagrams for my blog

https://blog.lysk.tech/excalidraw-frame-export/
143•mlysk•6h ago•66 comments

ChatGPT won't let you type until Cloudflare reads your React state

https://www.buchodi.com/chatgpt-wont-let-you-type-until-cloudflare-reads-your-react-state-i-decry...
779•alberto-m•17h ago•499 comments

How the AI Bubble Bursts

https://martinvol.pe/blog/2026/03/30/how-the-ai-bubble-bursts/
177•martinvol•1h ago•177 comments

How to Turn Anything into a Router

https://nbailey.ca/post/router/
5•yabones•20m ago•0 comments

Comprehensive C++ Hashmap Benchmarks (2022)

https://martin.ankerl.com/2022/08/27/hashmap-bench-01/
23•klaussilveira•4d ago•0 comments

Hamilton-Jacobi-Bellman Equation: Reinforcement Learning and Diffusion Models

https://dani2442.github.io/posts/continuous-rl/
83•sebzuddas•6h ago•20 comments

Spring Boot Done Right: Lessons from a 400-Module Codebase

https://medium.com/all-things-software/spring-boot-done-right-lessons-from-a-400-module-codebase-...
18•dknj•3d ago•4 comments

Voyager 1 runs on 69 KB of memory and an 8-track tape recorder

https://techfixated.com/a-1977-time-capsule-voyager-1-runs-on-69-kb-of-memory-and-an-8-track-tape...
597•speckx•21h ago•223 comments

Copilot edited an ad into my PR

https://notes.zachmanson.com/copilot-edited-an-ad-into-my-pr/
910•pavo-etc•9h ago•272 comments

VHDL's Crown Jewel

https://www.sigasi.com/opinion/jan/vhdls-crown-jewel/
89•cokernel_hacker•9h ago•32 comments

15 Years of Forking

https://www.waterfox.com/blog/15-years-of-forking/
231•MrAlex94•2d ago•43 comments

Ninja is a small build system with a focus on speed

https://github.com/ninja-build/ninja
46•tosh•3d ago•11 comments

C++26 is done: ISO C++ standards meeting Trip Report

https://herbsutter.com/2026/03/29/c26-is-done-trip-report-march-2026-iso-c-standards-meeting-lond...
269•pjmlp•20h ago•269 comments

Hardware Image Compression

https://www.ludicon.com/castano/blog/2026/03/hardware-image-compression/
44•luu•1d ago•8 comments

The First Video Game Was Just a Box in the Corner of a Bar

https://lithub.com/the-very-first-video-game-was-just-a-box-in-the-corner-of-a-bar/
20•PaulHoule•3d ago•16 comments

Philly courts will ban all smart eyeglasses starting next week

https://www.inquirer.com/news/philadelphia/smart-glasses-ai-meta-courts-20260326.html
317•Philadelphia•12h ago•141 comments

Douglas Lenat's Automated Mathematician Source Code

https://github.com/white-flame/am
41•hydrolox•4d ago•4 comments

My MacBook keyboard is broken and it's insanely expensive to fix

https://tobiasberg.net/posts/my-macbook-keyboard-is-broken-and-its-insanely-expensive-to-fix/
277•TobiasBerg•18h ago•318 comments

Pretext: TypeScript library for multiline text measurement and layout

https://github.com/chenglou/pretext
336•emersonmacro•1d ago•61 comments

Eclipse GlassFish: This Isn't Your Father's GlassFish

https://foojay.io/today/eclipse-glassfish-this-isnt-your-fathers-glassfish/
33•henk53•5d ago•30 comments

Midnight train from GA: A view of America from the tracks as airports struggle

https://apnews.com/article/airports-shutdown-long-lines-train-travel-amtrak-e4d8ea591b3b036142c2b...
122•walterbell•17h ago•105 comments

How A Spartan Revolutionized Baseball

https://msutoday.msu.edu/news/2026/03/spartan-revolutionize-baseball
17•rmason•4d ago•3 comments

15 years, one server, 8GB RAM and 500k users – how Webminal refuses to die

https://community.webminal.org/t/15-years-one-server-8gb-ram-and-500k-users-how-webminal-refuses-...
185•giis•7h ago•36 comments

Coding agents could make free software matter again

https://www.gjlondon.com/blog/ai-agents-could-make-free-software-matter-again/
224•rogueleaderr•15h ago•216 comments

"Roadrunner": a bipedal, wheeled robot for multi-modal locomotion [video]

https://www.youtube.com/watch?v=9kae-UAME1U
65•surprisetalk•4d ago•27 comments

Show HN: The Alphabetical Clock

https://boat.horse/clock/
22•secretdark•6h ago•13 comments

The road signs that teach travellers about France

https://www.bbc.com/travel/article/20260327-the-road-signs-that-teach-travellers-about-france
139•1659447091•17h ago•59 comments