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.

Ruff v0.16.0 – Significant new updates – 413 default rules up from 59

https://astral.sh/blog/ruff-v0.16.0
215•vismit2000•5h ago•123 comments

Go Analysis Framework: modular static analysis by go team

https://pkg.go.dev/golang.org/x/tools/go/analysis
67•AbuAssar•2h ago•6 comments

Google Discloses $94.1B in SpaceX Stock, Marking 6% Stake

https://www.wsj.com/tech/google-discloses-94-1-billion-in-spacex-stock-marking-6-stake-91655d7c
138•1vuio0pswjnm7•2h ago•67 comments

GrapheneOS protections against data extraction from locked devices

https://discuss.grapheneos.org/d/40700-grapheneos-protections-against-data-extraction-from-locked...
227•Cider9986•8h ago•117 comments

I learned PCB design, 3D printing and C just to listen to music

https://pentaton.app/blog/2026-07-12-introducing-pentaton-lp/
50•interfeco•3d ago•4 comments

A shell colon does nothing. Use it anyway

https://refp.se/articles/your-shell-and-the-magic-colon
306•olexsmir•1d ago•125 comments

Third Drone Shot Down in Three Days in Romanian Territory

https://english.mapn.ro/
146•_tk_•2h ago•140 comments

What's Under Your Feet in New York City?

https://practical.engineering/blog/2026/7/21/whats-under-your-feet-in-new-york-city
25•sohkamyung•4d ago•0 comments

The new rules of context engineering for Claude 5 generation models

https://claude.com/blog/the-new-rules-of-context-engineering-for-claude-5-generation-models
403•mellosouls•18h ago•293 comments

An ESP32 based plane radar for my desk

https://blog.ktz.me/esp32-plane-radar/
211•alexktz•12h ago•42 comments

DeepSeek pause fundraise after comments on compute gap to US leaked (transcript) [pdf]

https://github.com/demo-zexuan/liang-wenfeng-investor-meeting-2026-7-22/blob/master/%E6%A2%81%E6%...
205•oliculipolicula•15h ago•159 comments

Inflect-Micro-v2: complete voice in 9.36M parameters

https://huggingface.co/owensong/Inflect-Micro-v2
175•nateb2022•14h ago•14 comments

Ask HN: What are the most promising RL fields for a new master student?

17•zecice•1h ago•6 comments

Alien World Chemistry Found Inside Meteorite That Struck New Jersey Home

https://www.seti.org/news/alien-world-chemistry-found-inside-meteorite/
118•spzx•13h ago•40 comments

Show HN: I mapped every US golf course

https://golfcoursebrowser.com/
174•rickmf•12h ago•111 comments

What is happening to jobs? Separating AI hype from reality

https://siepr.stanford.edu/publications/policy-brief/what-really-happening-jobs-separating-ai-hyp...
164•pod_krad•16h ago•217 comments

Cloudflare's new AI traffic options for customers

https://blog.cloudflare.com/content-independence-day-ai-options/
155•alphabetatango•16h ago•131 comments

Stinkpot: SQLite-backed shell history

https://tangled.org/oppi.li/stinkpot
96•nerdypepper•2d ago•26 comments

Running a 28.9M parameter LLM on an $8 microcontroller

https://github.com/slvDev/esp32-ai
243•boveyking•19h ago•65 comments

DskDitto: Ultra-fast, parallel duplicate-file detector

https://github.com/jdefrancesco/dskDitto
44•ingve•4d ago•11 comments

I wouldn't say Pangram is broken, but I would say that it's brittle

https://freddiedeboer.substack.com/p/i-wouldnt-say-pangram-is-broken-but
39•antigizmo•2d ago•19 comments

Rethinking Legal Education in the AI Era

https://www.law.uchicago.edu/news/ai-strategy-statement
112•jjwiseman•2d ago•68 comments

Elevated Errors for Opus 5

https://status.claude.com/incidents/zftg3gqkmv18
62•TimCTRL•5h ago•56 comments

Pip install Postgres – no Docker/Brew/apt

https://github.com/leontrolski/postgresql-testing
23•leontrolski•2d ago•7 comments

LLM Usage in Debian: Three Proposals

https://www.debian.org/vote/2026/vote_002
191•zdw•19h ago•172 comments

Git rebase -I is not that scary

https://cachebag.sh/journal/interactive-rebasing/
98•vinhnx•14h ago•121 comments

Overloaded Overloading

https://powerfulpython.com/blog/overloaded-overloading/
30•redsymbol•4d ago•8 comments

Clinical failure rates over the decades: yikes

https://www.science.org/content/blog-post/clinical-failure-rates-over-decades-yikes
119•EA-3167•15h ago•107 comments

The hacker who humiliated spyware makers and was never caught

https://techcrunch.com/2026/07/25/the-hacker-who-humiliated-spyware-makers-and-was-never-caught/
3•Brajeshwar•23m ago•0 comments

SIMD for Collision

https://box2d.org/posts/2026/07/simd-for-collision/
120•birdculture•3d ago•30 comments