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.

ZCode: Claude Code from the Makers of GLM

https://zcode.z.ai/cn
143•handfuloflight•1h ago•51 comments

For first time, a cell built from scratch grows and divides

https://www.quantamagazine.org/for-the-first-time-a-cell-built-from-scratch-grows-and-divides-202...
569•defrost•6h ago•190 comments

What to Learn to Be a Graphics Programmer

https://blog.demofox.org/2026/07/01/what-to-learn-to-be-a-graphics-programmer/
119•atan2•2h ago•48 comments

Claude Fable 5 Promotional Access

https://support.claude.com/en/articles/15424964-claude-fable-5-promotional-access
50•zbikowski•59m ago•18 comments

FFmpeg 9.1's new AAC encoder

https://hydrogenaudio.org/index.php/topic,129691.0.html
161•ledoge•6h ago•61 comments

Physical disc production ending in Jan 2028 for new games on PlayStation

https://blog.playstation.com/2026/07/01/physical-disc-production-ending-in-january-2028-for-new-g...
417•Tiberium•8h ago•489 comments

Box3D, an open source 3D physics engine

https://box2d.org/posts/2026/06/announcing-box3d/
333•makepanic•8h ago•73 comments

How We Made IPFS Content Publishing 10x Faster

https://probelab.io/blog/optimistic-provide/
111•dennis-tra•5h ago•31 comments

Monetization Gateway

https://blog.cloudflare.com/monetization-gateway/
189•soheilpro•6h ago•102 comments

Internal Combustion Engine

https://ciechanow.ski/internal-combustion-engine/
210•StefanBatory•7h ago•44 comments

Ask HN: Who is hiring? (July 2026)

108•whoishiring•5h ago•123 comments

Fable 5 Is Back

https://twitter.com/claudeai/status/2072402636813607381
136•mfiguiere•54m ago•86 comments

Show HN: Z-Jail – A 130 KB Linux sandbox-C99 with 7 defense layers and zero deps

https://github.com/Division-36/Z-Jail/
10•Zierax•1h ago•5 comments

Hanami 3.0: In Full Bloom

https://hanakai.org/blog/2026/06/30/hanami-3-0-in-full-bloom
38•PuercoPop•2h ago•6 comments

Mortality associated with non-optimal ambient temperatures from 2000 to 2019

https://www.researchgate.net/publication/353058947_Global_regional_and_national_burden_of_mortali...
21•simonebrunozzi•3h ago•0 comments

Ask HN: Who wants to be hired? (July 2026)

80•whoishiring•5h ago•181 comments

A complete ClickHouse OLAP engine, compiled to WebAssembly

https://wasm.chdb.io/
28•porridgeraisin•3h ago•3 comments

1-Bit Pixel Art Emojis

https://hypertalking.com/2023/05/15/1-bit-pixel-art-emojis/
104•surprisetalk•6d ago•16 comments

Building Gin: Simple over Easy

https://manualmeida.dev/articles/gin-simple-over-easy/
49•manucorporat•2h ago•14 comments

Manufact (YC S25) Is Hiring a Developer Advocate in SF

https://www.ycombinator.com/companies/manufact/jobs/4cyWd6S-developer-advocate-partnerships-devrel
1•luigipederzani•7h ago

Sony Deletes 551 Movies PlayStation Owners Paid For

https://reclaimthenet.org/sony-deletes-551-studiocanal-movies-playstation-owners-paid-for
370•bilsbie•6h ago•176 comments

Launch HN: Parsewise (YC P25) – Reason Across Documents with an API

39•gergelycsegzi•6h ago•36 comments

Fixing a kubelet memory leak in Kubernetes 1.36

https://heyoncall.com/blog/fixing-kubernetes-kubelet-memory-leak
56•compumike•18h ago•12 comments

Reduce GVisor Cold Starts with GPU Snapshotting

https://cerebrium.ai/blog/reducing-gpu-cold-starts-with-memory-snapshots-restoring-cuda-workloads...
40•jono_irwin•4h ago•15 comments

Show HN: QR code renderer in a TrueType font

https://qr.jim.sh/
58•foodevl•3d ago•10 comments

Apple 'Hide My Email' vulnerability reveals peoples' real email addresses

https://easyoptouts.com/guides/apple-hide-my-email-is-leaking-email-addresses
195•sashk•10h ago•43 comments

Asahi Linux 7.1 Progress Report

https://asahilinux.org/2026/06/progress-report-7-1/
495•pantalaimon•10h ago•181 comments

Newly discovered spider builds spring loaded snare to catch ants

https://phys.org/news/2026-06-newly-australian-ballista-spider-snare.html
228•chimpanzee•3d ago•58 comments

Nintendo has raised its employees base salary by 10%

https://mynintendonews.com/2026/06/26/nintendo-has-raised-its-employees-base-salary-by-10/
465•_tk_•8h ago•279 comments

Red Programming Language: Static linking support

https://www.red-lang.org/2026/06/static-linking-support.html
65•em-bee•1d ago•11 comments