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

Teenage Engineering: Introducing APC-2

https://teenage.engineering/products/apc-2
80•vthommeret•1h ago•41 comments

DeepSeek V4 Pro beats GPT-5.5 Pro on precision

https://runtimewire.com/article/deepseek-v4-pro-beats-gpt-5-5-pro-on-precision
49•yogthos•58m ago•4 comments

The Smallest Brain You Can Build: A Perceptron in Python

https://ranpara.net/posts/perceptron-explained-from-scratch/
60•DevarshRanpara•2h ago•8 comments

Building from zero after addiction, prison, and a felony

https://gavinray97.github.io/blog/building-from-zero-after-addiction-prison-felony
436•gavinray•8h ago•195 comments

New drug 'functionally cures' many hepatitis B virus infections

https://www.science.org/content/article/new-drug-functionally-cures-many-hepatitis-b-virus-infect...
11•gmays•56m ago•0 comments

Show HN: I Derived a Pancake

https://www.absurdlyoptimized.com/recipes/pancakes/
134•bkazez•2d ago•41 comments

A Matter Wi-Fi Light Bulb in Rust on the Raspberry Pi Pico 2 W

https://github.com/melastmohican/rust-rpico2-embassy-examples
42•melastmohican•2h ago•3 comments

Algorithmic Monocultures in Hiring

https://algorithmichiring.github.io/
7•drchiu•42m ago•0 comments

Making peace with your unlived dreams (2023)

https://nik.art/making-peace-with-your-unlived-dreams/
159•herbertl•8h ago•78 comments

How's Linear so fast? A technical breakdown

https://performance.dev/how-is-linear-so-fast-a-technical-breakdown
310•howToTestFE•7h ago•159 comments

7.8 magnitude earthquake shakes part of southern Philippines. Tsunami possible

https://www.yahoo.com/news/weather-news/articles/as--philippines-earthquake-001322726.html
35•mikhael•1h ago•5 comments

What is the purpose of the lost+found folder in Linux and Unix? (2014)

https://unix.stackexchange.com/questions/18154/what-is-the-purpose-of-the-lostfound-folder-in-lin...
144•tosh•2d ago•51 comments

Do we fear the serializable isolation level more than we fear subtle bugs (2024)

https://blog.ydb.tech/do-we-fear-the-serializable-isolation-level-more-than-we-fear-subtle-bugs-5...
57•b-man•4d ago•31 comments

Powering up a module from the IBM 604: an electronic calculator from 1948

https://www.righto.com/2026/06/ibm-604-thyraton-tube-module.html
79•elpocko•9h ago•24 comments

Texas grid flags risks as data centers, crypto sites fail voltage tests

https://www.reuters.com/business/energy/texas-grid-flags-risks-data-centers-crypto-sites-fail-vol...
10•1vuio0pswjnm7•32m ago•0 comments

The 29th International Obfuscated C Code Contest (IOCCC) 2025 Winners

https://www.ioccc.org/2025/
368•matt_d•20h ago•88 comments

Show HN: Lathe – Use LLMs to learn a new domain, not skip past it

https://github.com/devenjarvis/lathe
249•devenjarvis•15h ago•48 comments

LLMs are eroding my software engineering career and I don't know what to do

https://human-in-the-loop.bearblog.dev/llms-are-eroding-my-software-engineering-career-and-i-dont...
822•poisonfountain•13h ago•809 comments

My automated doubt development process

https://www.alexself.dev/blog/automated-doubt
60•aself101•8h ago•17 comments

Firefox Merges Support for Vulkan Video Decoding

https://www.phoronix.com/news/Firefox-Vulkan-Video-Merged
76•Bender•3h ago•11 comments

Cloning a Sennheiser BA2015 battery pack

https://blog.brixit.nl/cloning-a-sennheiser-ba2015-accu-pack/
112•zdw•1d ago•17 comments

Proliferate (YC S25) is hiring to building open source Codex

https://www.ycombinator.com/companies/proliferate/jobs/L3copvK-founding-engineer
1•pablo24602•9h ago

KNN early termination in Manticore Search

https://manticoresearch.com/blog/knn-early-termination/
7•snikolaev•4d ago•0 comments

Back end is full of hidden workflows

https://unmeshed.io/blog/your-backend-is-full-of-hidden-workflows
3•jusonchan81•4d ago•0 comments

Splash Is a Colour Format

https://www.todepond.com/lab/splash/
53•tobr•4d ago•66 comments

Office-open-xml-viewer: Office XML document viewer that renders to HTML Canvas

https://github.com/yukiyokotani/office-open-xml-viewer
120•maxloh•9h ago•48 comments

A visual introduction to kernel functions

https://kelvinpaschal.com/blog/kernel-functions/
36•Kelvinidan•2d ago•9 comments

Backrest – a web UI and orchestrator for restic backup

https://github.com/garethgeorge/backrest
86•flexagoon•5d ago•7 comments

Podman 6: machine usability improvements (2025)

https://blog.podman.io/2025/10/podman-6-machine-usability-improvements/
101•daesorin•12h ago•6 comments

An Ohio Valley 100k-watt FM signal is severed in broad daylight

https://www.radioworld.com/news-and-business/headlines/an-ohio-valley-100000-watt-fm-signal-is-se...
155•pkaeding•1d ago•149 comments