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

Comments

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

Your job is to deliver code you have proven to work

https://simonwillison.net/2025/Dec/18/code-proven-to-work/
46•simonw•30m ago•36 comments

Classical statues were not painted horribly

https://worksinprogress.co/issue/were-classical-statues-painted-horribly/
185•bensouthwood•2h ago•92 comments

Please Just Try Htmx

http://pleasejusttryhtmx.com/
38•iNic•1h ago•21 comments

Virtualizing Nvidia HGX B200 GPUs with Open Source

https://www.ubicloud.com/blog/virtualizing-nvidia-hgx-b200-gpus-with-open-source
40•ben_s•1h ago•4 comments

Using TypeScript to Obtain One of the Rarest License Plates

https://www.jack.bio/blog/licenseplate
12•lafond•22m ago•2 comments

Are Apple gift cards safe to redeem?

https://daringfireball.net/linked/2025/12/17/are-apple-gift-cards-safe-to-redeem
77•tosh•56m ago•27 comments

Show HN: A local-first memory store for LLM agents (SQLite)

https://github.com/CaviraOSS/OpenMemory
14•nullure•4d ago•3 comments

Spain fines Airbnb €65M: Why the government is cracking down on illegal rentals

https://www.euronews.com/travel/2025/12/15/spain-fines-airbnb-65-million-why-the-government-is-cr...
31•robtherobber•33m ago•1 comments

Jonathan Blow has spent the past decade designing 1,400 puzzles for you

https://arstechnica.com/gaming/2025/12/jonathan-blow-has-spent-the-past-decade-designing-1400-puz...
142•furcyd•6d ago•167 comments

Slowness is a virtue

https://blog.jakobschwichtenberg.com/p/slowness-is-a-virtue
150•jakobgreenfeld•4h ago•55 comments

RCE via ND6 Router Advertisements in FreeBSD

https://www.freebsd.org/security/advisories/FreeBSD-SA-25:12.rtsold.asc
87•weeha•7h ago•44 comments

Creating apps like Signal could be 'hostile activity' claims UK watchdog

https://www.techradar.com/vpn/vpn-privacy-security/creating-apps-like-signal-or-whatsapp-could-be...
207•donohoe•4h ago•156 comments

Hightouch (YC S19) Is Hiring

https://hightouch.com/careers
1•joshwget•3h ago

Egyptian Hieroglyphs: Lesson 1

https://www.egyptianhieroglyphs.net/egyptian-hieroglyphs/lesson-1/
119•jameslk•9h ago•43 comments

Gemini 3 Flash: Frontier intelligence built for speed

https://blog.google/products/gemini/gemini-3-flash/
1052•meetpateltech•22h ago•552 comments

After ruining a treasured water resource, Iran is drying up

https://e360.yale.edu/features/iran-water-drought-dams-qanats
222•YaleE360•4h ago•165 comments

I got hacked: My Hetzner server started mining Monero

https://blog.jakesaunders.dev/my-server-started-mining-monero-this-morning/
509•jakelsaunders94•18h ago•318 comments

It's all about momentum

https://combo.cc/posts/its-all-about-momentum-innit/
81•sph•5h ago•26 comments

What is an elliptic curve? (2019)

https://www.johndcook.com/blog/2019/02/21/what-is-an-elliptic-curve/
108•tzury•8h ago•12 comments

Online Textbook for Braid groups and knots and tangles

https://matthematics.com/redoak/redoak.html
34•marysminefnuf•5h ago•2 comments

From profiling to kernel patch: the journey to an eBPF performance fix

https://rovarma.com/articles/from-profiling-to-kernel-patch-the-journey-to-an-ebpf-performance-fix/
17•todsacerdoti•4d ago•1 comments

Most parked domains now serving malicious content

https://krebsonsecurity.com/2025/12/most-parked-domains-now-serving-malicious-content/
64•bookofjoe•2h ago•16 comments

Show HN: X Writer – VS Code extension to post tweets from your editor

https://github.com/Jawuilp/X-writer
9•jawuilp•19h ago•4 comments

Coursera to combine with Udemy

https://investor.coursera.com/news/news-details/2025/Coursera-to-Combine-with-Udemy-to-Empower-th...
557•throwaway019254•1d ago•331 comments

AI helps ship faster but it produces 1.7× more bugs

https://www.coderabbit.ai/blog/state-of-ai-vs-human-code-generation-report
46•birdculture•2h ago•51 comments

Working quickly is more important than it seems (2015)

https://jsomers.net/blog/speed-matters
220•bschne•3d ago•108 comments

The Big City; Save the Flophouses (1996)

https://www.nytimes.com/1996/01/14/magazine/the-big-city-save-the-flophouses.html
18•ChadNauseam•3d ago•4 comments

Building a High-Performance OpenAPI Parser in Go

https://www.speakeasy.com/blog/building-speakeasy-openapi-go-library
30•subomi•3d ago•9 comments

Fluent: A Localization System for Natural-Sounding Translations

https://projectfluent.org/
14•stefankuehnel•4d ago•3 comments

Breaking Paragraphs into Lines [pdf] (1981)

https://gwern.net/doc/design/typography/tex/1981-knuth.pdf
26•Smaug123•6d ago•6 comments