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.

GLM-5.2 is the new leading open weights model on Artificial Analysis

https://artificialanalysis.ai/articles/glm-5-2-is-the-new-leading-open-weights-model-on-the-artif...
216•himata4113•2h ago•94 comments

Show HN: High-Res Neural Cellular Automata

https://cells2pixels.github.io/
72•esychology•2h ago•8 comments

RFC 10008: The new HTTP Query Method

https://www.rfc-editor.org/info/rfc10008/
24•schappim•1h ago•9 comments

GrapheneOS has been ported to Android 17

https://discuss.grapheneos.org/d/36469-grapheneos-has-been-ported-to-android-17-and-official-rele...
831•Cider9986•15h ago•420 comments

Running local models is good now

https://vickiboykis.com/2026/06/15/running-local-models-is-good-now/
1381•jfb•21h ago•531 comments

Hacker News but for Independent Blogs

https://bubbles.town/
167•headalgorithm•4h ago•55 comments

U.S. Science Is in Chaos

https://www.scientificamerican.com/article/americas-compact-between-science-and-politics-is-broken/
122•presspot•2h ago•85 comments

Show HN: Capacitor Alarm Clock

https://github.com/ArcaEge/capacitor-alarm-clock
32•arcaege•3d ago•10 comments

Humiliating IIS servers for fun and jail time

https://mll.sh/humiliating-iis-servers-for-fun-and-jail-time/
291•denysvitali•13h ago•67 comments

Map Clustering Is Not My Favorite

https://blog.greg.technology/2026/06/12/map-clustering-is-not-my-favorite.html
30•gregsadetsky•4d ago•13 comments

Subterranean fungi networks more than 100 quadrillion km in length

https://www.theguardian.com/science/2026/jun/11/arbuscular-mycorrhizal-fungi-plant-life-climate-g...
95•tosh•5d ago•21 comments

TIL: You can make HTTP requests without curl using Bash /dev/TCP

https://mareksuppa.com/til/bash-dev-tcp-http-without-curl/
448•mrshu•19h ago•203 comments

GLM 5.2 Performance Benchmarks

https://artificialanalysis.ai/models/glm-5-2
33•theanonymousone•4h ago•3 comments

Calvin and Hobbes and the price of integrity

https://therepublicofletters.substack.com/p/calvin-and-hobbes-and-the-price-of
453•pseudolus•20h ago•193 comments

Abandoned and Little-Known Airfields

https://airfields-freeman.com/
6•wizardforhire•2d ago•0 comments

Has AI already killed self-help nonfiction books?

https://tim.blog/2026/06/12/has-ai-already-killed-nonfiction/
327•imakwana•18h ago•376 comments

Wolfram Language and Mathematica version 15

https://writings.stephenwolfram.com/2026/06/launching-version-15-of-wolfram-language-mathematica-...
178•alok-g•12h ago•91 comments

GPT‑NL: a sovereign language model for the Netherlands

https://www.tno.nl/en/digital/artificial-intelligence/gpt-nl/
225•root-parent•18h ago•232 comments

Stop Using JWTs

https://gist.github.com/samsch/0d1f3d3b4745d778f78b230cf6061452
418•dzonga•19h ago•247 comments

The founder's playbook: Building an AI-native startup

https://claude.com/blog/the-founders-playbook
109•e2e4•4h ago•105 comments

Semiclassical Gravity Efficiently Solves NP-Complete Problems

https://arxiv.org/abs/2606.14806
40•ascarshen•8h ago•17 comments

From Chesterton's fence to Chesterton's gap

https://stephantul.github.io/blog/unfence/
16•stephantul•5h ago•14 comments

SpaceX to buy Cursor for $60B

https://www.reuters.com/legal/transactional/spacex-buy-anysphere-60-billion-2026-06-16/
1045•itsmarcelg•1d ago•1546 comments

But yak shaving is fun (2019)

https://parksb.github.io/en/article/32.html
272•parksb•21h ago•81 comments

Making 'food out of thin air' (2024)

https://www.noemamag.com/making-food-out-of-thin-air/
26•muchweight•2d ago•6 comments

Stop Killing Games fails to secure EU law despite 1.3M signatures

https://www.dexerto.com/gaming/stop-killing-games-fails-to-secure-eu-law-despite-1-3m-signatures-...
279•slymax•10h ago•209 comments

A brief tour of the PDP-11, the most influential minicomputer of all time (2022)

https://arstechnica.com/gadgets/2022/03/a-brief-tour-of-the-pdp-11-the-most-influential-minicompu...
87•jensgk•2d ago•36 comments

10Gb/s Ethernet: switching to a Broadcom SFP+ module

https://www.gilesthomas.com/2026/06/10g-ethernet-switching-to-broadcom-sfp-plus
161•gpjt•18h ago•143 comments

Lattice Triangles Are Rare

https://axiommath.ai/territory/the-reveal
21•skogstokig•6d ago•4 comments

Qwen-Robot Suite: A Foundation Model Suite for Physical World Intelligence

https://qwen.ai/blog?id=qwen-robotsuite
191•ilreb•22h ago•36 comments