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

Comments

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

New AirSnitch attack breaks Wi-Fi encryption in homes, offices, and enterprises

https://arstechnica.com/security/2026/02/new-airsnitch-attack-breaks-wi-fi-encryption-in-homes-of...
112•DamnInteresting•1h ago•48 comments

Nano Banana 2: Google's latest AI image generation model

https://blog.google/innovation-and-ai/technology/ai/nano-banana-2/
163•davidbarker•1h ago•150 comments

Open Source Endowment – new funding source for open source maintainers

https://endowment.dev/
32•kvinogradov•1h ago•11 comments

Show HN: Terminal Phone – E2EE Walkie Talkie from the Command Line

https://gitlab.com/here_forawhile/terminalphone
220•smalltorch•6h ago•54 comments

Anthropic ditches its core safety promise

https://www.cnn.com/2026/02/25/tech/anthropic-safety-policy-change
447•motbus3•4h ago•246 comments

Google API keys weren't secrets, but then Gemini changed the rules

https://trufflesecurity.com/blog/google-api-keys-werent-secrets-but-then-gemini-changed-the-rules
1032•hiisthisthingon•21h ago•248 comments

Bild AI (YC W25) Is Hiring Interns to Make Housing Affordable

https://www.workatastartup.com/jobs/80596
1•rooppal•21m ago

Palm OS User Interface Guidelines [pdf, 2003]

https://cs.uml.edu/~fredm/courses/91.308-spr05/files/palmdocs/uiguidelines.pdf
6•spiffytech•21m ago•1 comments

BuildKit: Docker's Hidden Gem That Can Build Almost Anything

https://tuananh.net/2026/02/25/buildkit-docker-hidden-gem/
43•jasonpeacock•3h ago•18 comments

just-bash: Bash for Agents

https://github.com/vercel-labs/just-bash
47•tosh•4h ago•33 comments

Will vibe coding end like the maker movement?

https://read.technically.dev/p/vibe-coding-and-the-maker-movement
15•itunpredictable•1h ago•6 comments

Tell HN: YC companies scrape GitHub activity, send spam emails to users

397•miki123211•7h ago•137 comments

Time Is Different

https://shkspr.mobi/blog/2026/02/this-time-is-different/
20•speckx•3h ago•14 comments

Jimi Hendrix was a systems engineer

https://spectrum.ieee.org/jimi-hendrix-systems-engineer
600•tintinnabula•21h ago•199 comments

Better to Skip a Year for Hardware Upgrades?

https://boilingsteam.com/poll-better-to-skip-a-year-for-pc-upgrades/
7•ekianjo•3d ago•3 comments

Those who can, teach history

https://www.historytoday.com/archive/making-history/those-who-can-teach-history
26•hhs•4d ago•25 comments

Banned in California

https://www.bannedincalifornia.org/
384•pie_flavor•18h ago•441 comments

How will OpenAI compete?

https://www.ben-evans.com/benedictevans/2026/2/19/how-will-openai-compete-nkg2x
394•iamskeole•18h ago•545 comments

Ferret-UI Lite: Lessons from Building Small On-Device GUI Agents

https://machinelearning.apple.com/research/ferret-ui
16•CharlesW•4d ago•2 comments

In 2025, Meta paid an effective federal tax rate of 3.5%

https://bsky.app/profile/rbreich.bsky.social/post/3mfptlfeucn2i
162•doener•2h ago•96 comments

First Website (1992)

https://info.cern.ch
284•shrikaranhanda•18h ago•81 comments

A 26-Gram Butterfly-Inspired Robot Achieving Autonomous Tailless Flight

https://arxiv.org/abs/2602.06811
50•Terretta•4d ago•12 comments

Story of XZ Backdoor [video]

https://www.youtube.com/watch?v=aoag03mSuXQ
60•Ulf950•3h ago•20 comments

Windows 11 Notepad to support Markdown

https://blogs.windows.com/windows-insider/2026/01/21/notepad-and-paint-updates-begin-rolling-out-...
332•andreynering•1d ago•500 comments

How AI skills are quietly automating my workday

https://medium.com/@ricardskrizanovskis/how-ai-skills-are-quietly-automating-my-workday-220a1b7b4707
17•rkrizanovskis•46m ago•12 comments

Making MCP cheaper via CLI

https://kanyilmaz.me/2026/02/23/cli-vs-mcp.html
290•thellimist•20h ago•112 comments

Artist who “paints” portraits on glass by hitting it with a hammer

https://simonbergerart.com
229•cs702•4d ago•99 comments

Bus stop balancing is fast, cheap, and effective

https://worksinprogress.co/issue/the-united-states-needs-fewer-bus-stops/
406•surprisetalk•1d ago•585 comments

Writers and Their Day Jobs

https://lithub.com/the-work-behind-the-writing-on-writers-and-their-day-jobs/
75•simplegeek•4d ago•26 comments

Some silly Z3 scripts I wrote

https://www.hillelwayne.com/post/z3-examples/
23•azhenley•3d ago•5 comments