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.

HackerTube: YouTube built from videos recommended by HN

https://karpathy.bearblog.dev/hacker-tube/
1685•karpathy•19h ago•445 comments

Novellas with Groff

https://movq.de/blog/postings/2026-10-31/0/POSTING-en.html
31•dverlaeckt80•2h ago•5 comments

Proving and Improving the Platonic Representation Hypothesis with JEPAs

https://arxiv.org/abs/2610.39302
39•Anon84•2h ago•8 comments

We Took over ChatGPT Accounts

https://simonwillison.net/2026/Oct/31/how-we-took-over-chatgpt-accounts/
4•paaloeye•12m ago•0 comments

Bidirectional Charging During Grid Outages

https://www.jefftk.com/p/bidirectional-charging-during-grid-outages
9•luu•19h ago•2 comments

Lenovo's 'encrypted' fingerprint USB is just an unencrypted SD card in a case

https://www.reddit.com/r/technology/comments/1xl2pr3/lenovos_encrypted_fingerprint_usb_drive_is_j...
70•entryleveljobsc•1h ago•25 comments

An Italian farmer found some unknown seeds in his attic and planted them

https://www.smithsonianmag.com/science-nature/italian-farmer-found-unknown-seeds-attic-with-nothi...
602•ecares•17h ago•173 comments

Show HN: I rebuilt my old canvas 3D library as a small WebGL 2 library – phoria2

https://kevs3d.co.uk/phoria2/
22•kevs3d•1d ago•3 comments

Police chief unplugs Flock cameras after company ignores contract cancellation

https://www.tomshardware.com/tech-industry/big-tech/police-chief-physically-unplugs-flock-cameras...
51•entryleveljobsc•1h ago•7 comments

One-minute frequency disturbances from synchronization in power systems

https://www.nature.com/articles/s41560-026-02144-0
36•croes•1d ago•13 comments

Brazilian Court Sanctions Lawyers for Prompt Injection in Court Filing

https://jetstream.security/insights/brazilian-court-sanctions-prompt-injection-filing/
218•doodlesdev•13h ago•110 comments

Memdoor: A team of 5 Qwen3.8-27B models beats Fable 5 on LiveCodeBench Hard

https://github.com/guregodevo/memdoor/tree/main/examples/workflows/team-solve
340•guregodevo•17h ago•165 comments

TCP Use-After-Free: CVE-2026-98432 / CVSS 9.8

https://atlasum.net/blog/cve-2026-98432-linux-ipv4-tcp-uaf
587•oger•20h ago•288 comments

Radiation Map of the World

https://radiaverse.com/
48•slater•3d ago•16 comments

The Ocean 'Was the Color of Chocolate.' Mexico Declares War on Seaweed.

https://www.nytimes.com/2026/10/28/world/americas/mexico-seaweed-navy.html
38•bookofjoe•1d ago•34 comments

Domain hacks with unusual Unicode characters (2018)

https://xn--69f31l4t57c0mag4b613h.xn--7uh4898msjaso/🆆🆃🅵/
34•n_plus_1_acc•5h ago•28 comments

Show HN: Point your camera at a landscape to learn about its geology

https://outcrop.rocks/
72•headsupernova•3d ago•18 comments

AI agent swarms in Minecraft fail to build civilization, drown in bureaucracy

https://www.tomshardware.com/tech-industry/artificial-intelligence/ai-agent-swarms-unleashed-in-m...
52•entryleveljobsc•2h ago•14 comments

Leaking Secrets from Air-Gap Computers by Spelling Radio Signals from RAM (2024)

https://arxiv.org/abs/2409.02292
138•hapax_legomena•14h ago•69 comments

Restrooms along the Norwegian Scenic Routes

https://www.visitnorway.com/plan-your-trip/travel-tips-a-z/norwegian-scenic-routes/worlds-best-to...
596•giuliomagnifico•5h ago•339 comments

Understanding Email Encryption

https://www.fastmail.com/blog/email-encryption/
70•nmjenkins•1d ago•15 comments

Running a bootstrapped SaaS for 20 years with my brother

https://blog.zamzar.com/2026/10/30/20-years-766-million-files-two-chameleons/
173•whyleyc•2d ago•43 comments

Copper – A minimal low-level programming language with OOP and generics

https://tibleiz.net/copper/
4•bogdanoff_2•1d ago•3 comments

Enlightenment 0.28.0 Release

https://www.enlightenment.org/news/2026-10-31-enlightenment-0.28.0
8•birdculture•27m ago•0 comments

Show HN: OmniDiff – Opensource, super fast, content aware Git difftool, in Rust

https://github.com/ivankovic/omnidiff
5•FabCH•2h ago•9 comments

The AI cost of JavaScript frameworks

https://nolanlawson.com/2026/10/28/the-ai-cost-of-javascript-frameworks/
182•luu•9h ago•123 comments

Altoids Project

https://uvdn7.github.io/altoids-project/
140•uvdn7•16h ago•7 comments

Zinc creep in cable spelter sockets brought down the Arecibo telescope in 2020

https://maketecheasier.com/arecibo-zinc-creep-collapse/
144•ohjeez•1d ago•44 comments

The "Moon Trees"

https://nssdc.gsfc.nasa.gov/planetary/lunar/moon_tree.html
20•momentmaker•2h ago•1 comments

A 1580 Map Shows Why Data Visualization Is Never Neutral

https://thereader.mitpress.mit.edu/a-1580-map-shows-why-data-visualization-is-never-neutral/
70•the-mitr•2d ago•8 comments