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

Comments

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

Google will allow users to sideload Android apps without verification

https://android-developers.googleblog.com/2025/11/android-developer-verification-early.html
663•erohead•6h ago•267 comments

Steam Machine

https://store.steampowered.com/sale/steammachine
1730•davikr•13h ago•848 comments

Steam Frame

https://store.steampowered.com/sale/steamframe
1256•Philpax•13h ago•479 comments

Android 16 QPR1 is being pushed to the Android Open Source Project

https://grapheneos.social/@GrapheneOS/115533432439509433
67•uneven9434•3h ago•17 comments

The last-ever penny will be minted today in Philadelphia

https://www.cnn.com/2025/11/12/business/last-penny-minted
646•andrewl•15h ago•808 comments

Human Fovea Detector

https://www.shadertoy.com/view/4dsXzM
125•AbuAssar•6h ago•26 comments

Mergiraf: Syntax-Aware Merging for Git

https://lwn.net/SubscriberLink/1042355/434ad706cc594276/
54•Velocifyer•1w ago•8 comments

Project Euler

https://projecteuler.net
405•swatson741•13h ago•98 comments

Comparing the Latitude of Europe and America

https://vividmaps.com/comparing-latitude-of-europe-and-america/
27•mooreds•4d ago•9 comments

Marble: A Multimodal World Model

https://www.worldlabs.ai/blog/marble-world-model
174•meetpateltech•9h ago•41 comments

GPT-5.1: A smarter, more conversational ChatGPT

https://openai.com/index/gpt-5-1/
299•tedsanders•12h ago•320 comments

CollectWise (YC F24) Is Hiring

https://www.ycombinator.com/companies/collectwise/jobs/tv3ufcc-forward-deployed-engineer
1•OBrien_1107•2h ago

Meta replaces WhatsApp for Windows with web wrapper that uses 1 GB RAM when idle

https://www.windowslatest.com/2025/11/12/meta-just-killed-native-whatsapp-on-windows-11-now-it-op...
107•DearAll•3h ago•31 comments

Bitcoin's big secret: How cryptocurrency became law enforcement's secret weapon

https://bitwarden.com/blog/how-cryptocurrency-became-law-enforcements-secret-weapon/
87•LopRabbit•3h ago•42 comments

Large integer precision error in Bash command output rendering

https://github.com/anthropics/claude-code/issues/11506
26•rrwright•3h ago•26 comments

Transpiler, a Meaningless Word (2023)

https://people.csail.mit.edu/rachit/post/transpiler/
12•jumploops•6d ago•3 comments

Learn Prolog Now

https://lpn.swi-prolog.org/lpnpage.php?pageid=top
264•rramadass•16h ago•182 comments

Fighting the New York Times' invasion of user privacy

https://openai.com/index/fighting-nyt-user-privacy-invasion
327•meetpateltech•17h ago•298 comments

Valve is about to win the console generation

https://xeiaso.net/blog/2025/valve-is-about-to-win-the-console-generation/
181•moonleay•7h ago•159 comments

Helm 4.0

https://github.com/helm/helm/releases/tag/v4.0.0
64•todsacerdoti•14h ago•68 comments

On USB HID, Keyboard LEDs, and device emulation (2024)

https://epsilon537.github.io/boxlambda/usb-hid/
16•transpute•3h ago•1 comments

Yt-dlp: External JavaScript runtime now required for full YouTube support

https://github.com/yt-dlp/yt-dlp/issues/15012
940•bertman•21h ago•555 comments

Digital ID, a new way to create and present an ID in Apple Wallet

https://www.apple.com/newsroom/2025/11/apple-introduces-digital-id-a-new-way-to-create-and-presen...
89•meetpateltech•14h ago•121 comments

Launch HN: JSX Tool (YC F25) – A Browser Dev-Panel IDE for React

97•jsunderland323•13h ago•72 comments

GLP-1 drugs linked to lower death rates in colon cancer patients

https://today.ucsd.edu/story/glp-1-drugs-linked-to-dramatically-lower-death-rates-in-colon-cancer...
115•gmays•11h ago•108 comments

Homebrew no longer allows bypassing Gatekeeper for unsigned/unnotarized software

https://github.com/Homebrew/brew/issues/20755
194•firexcy•9h ago•160 comments

Strap Rail

https://www.construction-physics.com/p/strap-rail
4•surprisetalk•3d ago•0 comments

How Tube Amplifiers Work

https://robrobinette.com/How_Amps_Work.htm
95•gokhan•12h ago•51 comments

Voyager 1 is a light-day away by November 2026

https://www.iflscience.com/on-november-13-2026-voyager-will-reach-one-full-light-day-away-from-ea...
189•Neuronaut•7h ago•62 comments

A Commentary on the Sixth Edition Unix Operating System

https://warsus.github.io/lions-/
16•o4c•4h ago•2 comments