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•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();
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.

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

DeepSeek reasonix, DeepSeek native coding agent with high caching and low cost

https://esengine.github.io/DeepSeek-Reasonix/
313•Alifatisk•7h ago•159 comments

Migrating from Go to Rust

https://corrode.dev/learn/migration-guides/go-to-rust/
20•jabits•2h ago•0 comments

Memory has grown to nearly two-thirds of AI chip component costs

https://epoch.ai/data-insights/ai-chip-component-cost-shares
207•intelkishan•4h ago•226 comments

Using HTTP/2 Cleartext for a server in Go 1.24

https://www.clarityboss.com/blog/go-http2-cleartext-h2c-cloud-run
13•dan_sbl•5d ago•2 comments

Australia Four-Day Work Week Study Data Shows Boosted Productivity

https://scienceaim.com/australia-just-proved-the-four-day-work-week-works-here-is-what-the-data-a...
52•randycupertino•1h ago•15 comments

CBP Directive 3340-049B: Border Search of Electronic Devices

https://www.cbp.gov/document/directives/cbp-directive-no-3340-049b-border-search-electronic-devices
8•Ember_Wipe•1h ago•0 comments

Constraint Decay: The Fragility of LLM Agents in Back End Code Generation

https://arxiv.org/abs/2605.06445
132•wek•7h ago•65 comments

Claude is not your architect. Stop letting it pretend

https://www.hollandtech.net/claude-is-not-your-architect/
159•cdrnsf•2h ago•104 comments

I spent 50 hours drawing a line graph

https://www.dougmacdowell.com/50-hours-to-draw-some-lines.html
362•dougdude3339•3d ago•64 comments

Don't know where your data is from? Bayesian modeling for unknown coordinates

https://christopherkrapu.com/blog/2026/dont-know-where-your-data-is-from/
17•ckrapu•3h ago•0 comments

Mastering Dyalog APL

https://mastering.dyalog.com/README.html
114•tosh•9h ago•29 comments

Noroboto: Lying Fonts and Mitigation in Rust

https://tritium.legal/blog/noroboto
31•piker•2d ago•19 comments

The political polarization of health outcomes in the USA

https://www.nature.com/articles/s41562-026-02474-9
29•geox•1h ago•8 comments

Flick (YC F25) Is Hiring Front End Engineer to Build Figma for AI Filmmaking

https://www.ycombinator.com/companies/flick/jobs/Tdu6FH6-senior-frontend-engineer
1•rayruiwang•3h ago

Build Adafruit projects right from Firefox

https://www.firefox.com/en-US/landing/adafruit/
64•mch82•2d ago•15 comments

Microsoft open-sources "the earliest DOS source code discovered to date"

https://arstechnica.com/gadgets/2026/04/microsoft-open-sources-the-earliest-dos-source-code-disco...
398•DamnInteresting•19h ago•131 comments

Defeating Git Rigour Fatigue with Jujutsu

https://ikesau.co/blog/defeating-git-rigour-fatigue-with-jujutsu/
6•ikesau•2h ago•0 comments

Greg Brockman interview [video]

https://fs.blog/knowledge-project-podcast/greg-brockman/
149•prakashqwerty•12h ago•133 comments

Ruby for Good

https://ti.to/codeforgood/rubyforgood
94•mooreds•5h ago•36 comments

Childhood Computing

https://susam.net/childhood-computing.html
131•blenderob•8h ago•70 comments

Usborne 1980s Computer Books

https://usborne.com/us/books/computer-and-coding-books
131•ngram•5h ago•41 comments

Perceptual Image Codec: What Matters in Practical Learned Image Compression

https://apple.github.io/ml-pico/
70•ksec•8h ago•21 comments

I keep bouncing off the Scheme language

https://www.sicpers.info/2026/05/i-keep-bouncing-off-the-scheme-language/
115•ingve•2d ago•44 comments

DeepSeek to Make Permanent 75% Discount on Flagship AI Model

https://www.bloomberg.com/news/articles/2026-05-23/deepseek-to-make-permanent-75-discount-on-flag...
164•moh_maya•6h ago•2 comments

Scammers are abusing an internal Microsoft account to send spam links

https://techcrunch.com/2026/05/21/scammers-are-abusing-an-internal-microsoft-account-to-send-spam/
248•spike021•20h ago•137 comments

Curly braces: An evolution of Unix and C

https://thalia.dev/blog/unix-braces/
41•thaliaarchi•4d ago•8 comments

Wake up! 16b

https://hellmood.111mb.de/wake_up_16b_writeup.html
386•MaximilianEmel•20h ago•28 comments

Why is Vivado 2026.1 dropping Linux support for free tier?

https://adaptivesupport.amd.com/s/question/0D5Pd00001YQLdMKAX/why-is-vivado-20261-dropping-linux-...
274•zdw•16h ago•161 comments

Book Review: On the Calculation of Volume

https://www.stephendiehl.com/posts/calculation_of_volume/
14•ibobev•3d ago•3 comments

Understanding WebAuthn credential protection policy

https://pilcrowonpaper.com/blog/16
3•mooreds•2h ago•0 comments