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.

Tailscale didn't stop the Hugging Face intrusion

https://tailscale.com/blog/hugging-face-intrusion
383•bluehatbrit•5h ago•153 comments

Elevators

https://john.fun/elevators
817•Jrh0203•8h ago•211 comments

qm

https://github.com/yc-software/qm
397•tosh•6h ago•89 comments

Twenty-five years ago it was cryptography, today it's model weights

https://weeraman.com/because-we-can/
109•aweeraman•3d ago•39 comments

The Absurdity of Albert Camus

https://www.historytoday.com/archive/portrait-author-historian/absurdity-albert-camus
29•apollinaire•1d ago•12 comments

Progressive Web Components

https://arielsalminen.com/2026/progressive-web-components/
63•hosteur•14h ago•10 comments

June in Servo: real world compat, media queries, SharedWorker, and more

https://servo.org/blog/2026/07/31/june-in-servo/
91•iamnothere•5h ago•29 comments

Big Food vs. the People

https://www.lighthousereports.com/investigation/big-food-vs-the-people/
179•jruohonen•8h ago•121 comments

Demystifying DRAM Read Disturbance: RowHammer and RowPress Phenomena

https://arxiv.org/abs/2607.28233
24•Jimmc414•3h ago•14 comments

Golang proposal: container/: generic collection types

https://github.com/golang/go/issues/80590
112•jabits•5h ago•66 comments

DeepSeek V4 Flash 0731 Intelligence, Performance and Price Analysis

https://artificialanalysis.ai/models/deepseek-v4-flash
520•theanonymousone•16h ago•288 comments

Loops (YC W22) Is Hiring a Product Educator

https://www.ycombinator.com/companies/loops/jobs/zqUnwqB-product-educator-technical-content-creator
1•chrisfrantz•3h ago

The First Transatlantic Telegraph Cable Was a Bold, Beautiful Failure

https://spectrum.ieee.org/the-first-transatlantic-telegraph-cable-was-a-bold-beautiful-failure
13•sparsesignal•2d ago•2 comments

Run Kimi K3 using 29 GB of RAM at 0.50 tok/s

https://github.com/sqliteai/waste
132•marcobambini•9h ago•54 comments

Let's make the worst Htmx

https://zserge.com/posts/worst-htmx-ever/
53•RebelPotato•18h ago•13 comments

Termixer (TUI DJ Mixer)

https://github.com/l00sed/termixer
46•l00sed•5h ago•32 comments

How JPEG works: Interactively explore JPEG's lossy compression methods

https://cgjennings.ca/articles/jpeg-compression/
93•at1as•4d ago•11 comments

Getting 25 Gbps Thunderbolt Ethernet on My Mac Studio

https://www.jeffgeerling.com/blog/2026/getting-25g-ethernet-mac-thunderbolt/
120•speckx•7h ago•76 comments

The most official water costs $120k a gallon

https://signoregalilei.com/2026/07/26/the-most-official-water-costs-120000-a-gallon/
124•surprisetalk•9h ago•100 comments

Authorize, don't authenticate

https://blog.marcua.net/2026/07/31/authorize-dont-authenticate.html
45•marcua•9h ago•10 comments

Everyone is building LLM routers, we deprecated ours

https://manifest.build/blog/why-we-deprecated-our-llm-router/
83•brunaxLorax•6h ago•39 comments

Dubious research tied to Red Bull has shaped energy drink policy

https://www.theexamination.org/articles/red-bull-funded-research-energy-drinks-alcohol
104•Jimmc414•8h ago•162 comments

Predictive Speculative KV Replication for Bursty LLM Inference

https://jwlabs.vercel.app/post/biting-the-bullet
20•shreybirmiwal•4h ago•1 comments

Is AI reasoning right for the wrong reasons?

https://www.quantamagazine.org/is-ai-reasoning-right-for-the-wrong-reasons-20260731/
108•retupmoc01•8h ago•141 comments

Using the railway network as a flatbed scanner [video]

https://media.ccc.de/v/emf2026-74-1-using-the-railway-network-as-a-flatbed-scanner
43•Jimmc414•5h ago•21 comments

Algorithms on billion-scale graph using 10GB RAM: I love DataFusion

https://semyonsinchenko.github.io/ssinchenko/post/datafusion-graphs-cc-2/
92•speckx•8h ago•31 comments

Britain's New World of Tobacco (2017)

https://www.historytoday.com/archive/feature/britains-new-world-tobacco
7•benbreen•2d ago•0 comments

A past and future of trade secrets

https://www.cabinetmagazine.org/issues/70/kofen.php
7•Hooke•1d ago•0 comments

Severance

https://lcamtuf.substack.com/p/severance
192•surprisetalk•6h ago•58 comments

Show HN: How to build and self-host a code review agent

https://www.trytilde.ai/blog/how-to-build-code-review-agent
16•solsol94•3h ago•3 comments