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•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.

The intracies of modern camera lens repair (2024)

https://salvagedcircuitry.com/sigma-45mm.html
41•transistor-man•1h ago•2 comments

Astronauts told to return to ISS after sheltering over air leak repairs

https://www.bbc.com/news/live/c4g44ew3g1kt
359•janpot•10h ago•232 comments

pg_durable: Microsoft open sources in-database durable execution

https://github.com/microsoft/pg_durable
326•coffeemug•9h ago•78 comments

Gemma 4 QAT models: Optimizing compression for mobile and laptop efficiency

https://blog.google/innovation-and-ai/technology/developers-tools/quantization-aware-training-gem...
271•theanonymousone•9h ago•86 comments

New method turns ocean water into drinking water, without waste

https://www.rochester.edu/newscenter/what-is-desalination-definition-ocean-water-704732/
256•speckx•10h ago•115 comments

Show HN: ABC Classic 100 Rankings visualised

https://classic100.gotski.workers.dev/
8•gotski•27m ago•2 comments

Mouseless – keyboard-driven control of macOS/Linux/Windows

https://mouseless.click
454•riddley•2d ago•190 comments

Did Claude increase bugs in rsync?

https://alexispurslane.github.io/rsync-analysis/
307•logicprog•13h ago•311 comments

My Agent Skill for Test-Driven Development

https://www.saturnci.com/my-agent-skill-for-test-driven-development.html
133•laxmena•1d ago•53 comments

Gov.uk has replaced Stripe with Dutch provider Adyen

https://www.theregister.com/public-sector/2026/06/04/govuk-goes-dutch-on-payments-as-it-dumps-str...
357•toomuchtodo•9h ago•125 comments

The Quiet Numbers Station: Decoding Nineteen Years of GPS Cryptography

https://www.benthamsgaze.org/2026/06/02/the-quiet-numbers-station-decoding-nineteen-years-of-gps-...
64•lordgilman•13h ago•66 comments

Conventional Commits encourages focus on the wrong things

https://sumnerevans.com/posts/software-engineering/stop-using-conventional-commits/
267•jsve•10h ago•209 comments

Ask HN: What was your "oh shit" moment with GenAI?

167•andrehacker•1d ago•395 comments

Transformers are inherently succinct

https://openreview.net/pdf?id=Yxz92UuPLQ
90•brandonb•7h ago•30 comments

Nordstjernen Web Browser 1.0.0 released

https://github.com/nordstjernen-web/nordstjernen/releases/tag/1.0.0
9•andreasrosdal•2h ago•0 comments

I tested every IP KVM in my Homelab

https://www.jeffgeerling.com/blog/2026/i-tested-every-ip-kvm/
242•vquemener•11h ago•66 comments

Launch HN: General Instinct (YC P26) – Frontier models on edge devices

46•guanming0717•9h ago•14 comments

India's surprise baby bust

https://www.economist.com/leaders/2026/06/04/indias-surprise-baby-bust-is-a-warning-to-the-world
133•hakonbogen•11h ago•588 comments

Cooldown Support for Ruby Bundler

https://blog.rubygems.org/2026/06/03/cooldown-let-new-gems-be-vetted.html
144•calyhre•2d ago•39 comments

"Maybe later" was a feature

https://arnorhs.dev/posts/2026-06-04/maybe-later-was-a-feature/
78•arnorhs•1d ago•26 comments

Europe's largest Copper Age tomb: children's bones show ancient health crisis

https://phys.org/news/2026-05-europe-largest-copper-age-tomb.html
7•gmays•1d ago•3 comments

Tracing a powerful GNSS interference source over Europe

https://arxiv.org/abs/2606.03673
363•mimorigasaka•17h ago•197 comments

Aging and Eye Problems

https://ldstephens.net/posts/aging-and-eye-problems/
54•speckx•7h ago•24 comments

The perils of UUID primary keys in SQLite

https://andersmurphy.com/2026/06/05/the-perils-of-uuid-primary-keys-in-sqlite.html
22•emschwartz•2h ago•10 comments

Inside FAISS: Billion-Scale Similarity Search

https://fremaconsulting.ch/blog/faiss
46•tohms•1d ago•3 comments

C++: The Documentary

https://herbsutter.com/2026/06/04/c-the-documentary-released-today/
376•ingve•21h ago•271 comments

Mantine-datatable (and others) compromised – owner account suspended

https://github.com/icflorescu/mantine-datatable/discussions/813
61•justsomehuman•9h ago•24 comments

Redis 8.8: New array data structure, rate limiter, performance improvements

https://redis.io/blog/announcing-redis-8-8/
203•ksec•2d ago•92 comments

South Korean forums will need to scan every images with AI censorship tools

https://discuss.privacyguides.net/t/south-korean-online-communities-will-need-to-scan-every-image...
224•Cider9986•1d ago•133 comments

Show HN: Lowfat – pluggable CLI filter that saved 91.8% of my LLM tokens

https://github.com/zdk/lowfat
115•zdkaster•16h ago•58 comments