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";
  }

Ggml.ai joins Hugging Face to ensure the long-term progress of Local AI

https://github.com/ggml-org/llama.cpp/discussions/19759
8•lairv•13m ago•0 comments

The path to ubiquitous AI (17k tokens/sec)

https://taalas.com/the-path-to-ubiquitous-ai/
327•sidnarsipur•3h ago•227 comments

Nvidia and OpenAI abandon unfinished $100B deal in favour of $30B investment

https://www.ft.com/content/dea24046-0a73-40b2-8246-5ac7b7a54323
142•zerosizedweasle•2h ago•87 comments

Untapped Way to Learn a Codebase: Build a Visualizer

https://jimmyhmiller.com/learn-codebase-visualizer
71•andreabergia•5h ago•16 comments

Web Components: The Framework-Free Renaissance

https://www.caimito.net/en/blog/2026/02/17/web-components-the-framework-free-renaissance.html
78•mpweiher•5h ago•45 comments

Gemini 3.1 Pro

https://blog.google/innovation-and-ai/models-and-research/gemini-models/gemini-3-1-pro/
838•MallocVoidstar•22h ago•850 comments

Mothers (YC X26) Is Hiring

https://jobs.ashbyhq.com/9-mothers?utm_source=x8pZ4B3P3Q
1•ukd1•20m ago

Consistency diffusion language models: Up to 14x faster, no quality loss

https://www.together.ai/blog/consistency-diffusion-language-models
158•zagwdt•9h ago•52 comments

Raspberry Pi Pico 2 at 873.5MHz with 3.05V Core Abuse

https://learn.pimoroni.com/article/overclocking-the-pico-2
61•Lwrless•5h ago•8 comments

The Rediscovery of 103 Hokusai Lost Sketches (2021)

https://japan-forward.com/eternal-hokusai-the-rediscovery-of-103-hokusai-lost-sketches/
11•debo_•4d ago•0 comments

Defer available in gcc and clang

https://gustedt.wordpress.com/2026/02/15/defer-available-in-gcc-and-clang/
216•r4um•4d ago•163 comments

AI is not a coworker, it's an exoskeleton

https://www.kasava.dev/blog/ai-as-exoskeleton
344•benbeingbin•18h ago•381 comments

Minions – Stripe's Coding Agents Part 2

https://stripe.dev/blog/minions-stripes-one-shot-end-to-end-coding-agents-part-2
42•ludovicianul•2h ago•24 comments

I tried building my startup entirely on European infrastructure

https://www.coinerella.com/made-in-eu-it-was-harder-than-i-thought/
467•willy__•5h ago•239 comments

Infrastructure decisions I endorse or regret after 4 years at a startup (2024)

https://cep.dev/posts/every-infrastructure-decision-i-endorse-or-regret-after-4-years-running-inf...
322•Meetvelde•3d ago•140 comments

Show HN: Micasa – track your house from the terminal

https://micasa.dev
584•cpcloud•22h ago•189 comments

FreeCAD

https://www.freecad.org/index.php
253•doener•3d ago•96 comments

Reading the undocumented MEMS accelerometer on Apple Silicon MacBooks via iokit

https://github.com/olvvier/apple-silicon-accelerometer
86•todsacerdoti•8h ago•49 comments

US plans online portal to bypass content bans in Europe and elsewhere

https://www.reuters.com/world/us-plans-online-portal-bypass-content-bans-europe-elsewhere-2026-02...
380•c420•1d ago•700 comments

Exercise has 'similar effect' to therapy, study on depression shows

https://medicalxpress.com/news/2026-01-similar-effect-therapy-depression.html
59•PaulHoule•1h ago•57 comments

A beginner's guide to split keyboards

https://www.justinmklam.com/posts/2026/02/beginners-guide-split-keyboards/
176•thehaikuza•4d ago•189 comments

Fast KV Compaction via Attention Matching

https://arxiv.org/abs/2602.16284
47•cbracketdash•9h ago•2 comments

Silicon Valley engineers were indicted for allegedly sending secrets to Iran

https://www.cnbc.com/2026/02/20/three-engineers-charged-stealing-google-trade-secrets-data-iran-s...
36•giuliomagnifico•3h ago•4 comments

Notes on Clarifying Man Pages

https://jvns.ca/blog/2026/02/18/man-pages/
22•surprisetalk•1d ago•10 comments

An ARM Homelab Server, or a Minisforum MS-R1 Review

https://sour.coffee/2026/02/20/an-arm-homelab-server-or-a-minisforum-ms-r1-review/
90•neelc•12h ago•77 comments

America vs. Singapore: You can't save your way out of economic shocks

https://www.governance.fyi/p/america-vs-singapore-you-cant-save
292•guardianbob•23h ago•434 comments

Pi for Excel: AI sidebar add-in for Excel

https://github.com/tmustier/pi-for-excel
88•rahimnathwani•11h ago•25 comments

Micropayments as a reality check for news sites

https://blog.zgp.org/micropayments-as-a-reality-check-for-news-sites/
177•speckx•18h ago•350 comments

An AI Agent Published a Hit Piece on Me – The Operator Came Forward

https://theshamblog.com/an-ai-agent-wrote-a-hit-piece-on-me-part-4/
453•scottshambaugh•10h ago•382 comments

Paged Out Issue #8 [pdf]

https://pagedout.institute/download/PagedOut_008.pdf
407•SteveHawk27•1d ago•61 comments