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.

SearXNG: A free internet metasearch engine

https://github.com/searxng/searxng
17•theanonymousone•54m ago•2 comments

Costco is the anti-Amazon

https://phenomenalworld.org/analysis/the-anti-amazon/
175•bookofjoe•5h ago•138 comments

Jamesob's guide to running SOTA LLMs locally

https://github.com/jamesob/local-llm
206•livestyle•6h ago•99 comments

FreeBSD ate my RAM

https://crocidb.com/post/freebsd-ate-my-ram/
33•theanonymousone•2h ago•4 comments

Pet projects are getting too big to pet

https://www.nnehdi.me/p/pet-projects-are-getting-too-big
10•nnehdi•57m ago•2 comments

Infracost (YC W21) Is Hiring a Marketing Lead to Shift FinOps Left

https://www.ycombinator.com/companies/infracost/jobs/YTJcFwr-marketing-lead
1•akh•9m ago

Factories are just rooms

https://interconnected.org/home/2026/07/03/factories
143•arbesman•5h ago•60 comments

Espionage Against the European Parliament

https://citizenlab.ca/research/member-of-committee-investigating-spyware-hacked-with-pegasus/
4•ledoge•32m ago•0 comments

Kagi Changelog (July 2): Heads, tails, and an AI toggle

https://kagi.com/changelog#10959
5•mroche•1h ago•0 comments

Hunting a 16-year-old SQLite WAL bug with TLA+

https://ubuntu.com/blog/hunting-a-16-year-old-sqlite-bug-with-tla-is-dqlite-affected
141•peterparker204•3d ago•8 comments

Show HN: Mcpsnoop – Wireshark for MCP (transparent proxy and live TUI)

https://github.com/kerlenton/mcpsnoop
35•kerlenton•4h ago•12 comments

PostgreSQL and the OOM killer: Why we use strict memory overcommit

https://www.ubicloud.com/blog/postgresql-and-the-oom-killer-why-we-use-strict-memory-overcommit
133•furkansahin•8h ago•70 comments

My dad helped build North America's oat supply chain: Can it be remade?

https://ambrook.com/offrange/perspective/how-we-lost-our-oats
70•surprisetalk•3d ago•34 comments

Wordgard: In-browser rich-text editor from the creator of ProseMirror

https://wordgard.net/
225•indy•12h ago•82 comments

Valve open-source the Steam Machine e-ink screen so you can make your own

https://www.gamingonlinux.com/2026/07/valve-open-source-the-steam-machine-e-ink-screen-so-you-can...
478•ahlCVA•8h ago•83 comments

Farmer, marketer at odds over sales of white nectarines

https://apnews.com/article/california-farmer-nectarines-lawsuit-patent-4f7bc8ab185e8b9cbdd6d6ad4f...
95•djoldman•2h ago•91 comments

60% Fable cost cut by converting code to images and having the model OCR it

https://github.com/teamchong/pxpipe
162•dimitropoulos•5h ago•59 comments

Half-Baked Product

https://weli.dev/blog/half-baked-product/
1149•weli•12h ago•350 comments

Oak: Git for Agents

https://oak.space/
10•handfuloflight•1h ago•5 comments

Best Simple System for Now (2025)

https://dannorth.net/blog/best-simple-system-for-now/
64•daan-k•6h ago•14 comments

Ask HN: Is anyone experimenting with different ways of using LLMs for coding?

80•yehiaabdelm•14h ago•101 comments

The Fall and Rise of Screwworm

https://www.construction-physics.com/p/the-fall-and-rise-of-screwworm
116•crescit_eundo•8h ago•44 comments

Holes

https://xkcd.com/3266/large/
88•caminanteblanco•3h ago•15 comments

Flexible metaprogramming with Rhombus

https://lwn.net/SubscriberLink/1079001/67840550991151ed/
92•spdegabrielle•1d ago•1 comments

International chess federation sanctions Kramnik

https://www.fide.com/fide-ethics-disciplinary-commission-issues-a-decision-in-case-involving-gm-v...
84•DarkContinent•4h ago•39 comments

Why Being Overqualified Is a Risk

https://newsletter.bphogan.com/archive/issue-52-run-coding-models-locally-and-why-being/
3•mooreds•1h ago•0 comments

Instead of banning AI, I made a classroom contract with my students

https://www.science.org/content/article/instead-banning-ai-i-made-classroom-contract-my-students
59•digital55•6h ago•53 comments

America, 1926: A forgotten 100-year-old report

https://www.derekthompson.org/p/america-1926-an-absurdly-deep-dive
110•momentmaker•6h ago•146 comments

Supersonic flight returning to US after half-century ban

https://www.forbes.com/sites/suzannerowankelleher/2026/06/30/faa-supersonic-flight-no-boom/
131•lobbly•2d ago•156 comments

The Life and Times of Maxis, Part 1: SimEverything

https://www.filfre.net/2026/07/the-life-and-times-of-maxis-part-1-simeverything/
89•doppp•5h ago•5 comments