frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

Understanding Java's Asynchronous Journey

https://amritpandey.io/understanding-javas-asynchronous-journey/
17•hardasspunk•2mo ago

Comments

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

Asynchrony is not concurrency

https://kristoff.it/blog/asynchrony-is-not-concurrency/
151•kristoff_it•4h ago•104 comments

Shutting Down Clear Linux OS

https://community.clearlinux.org/t/all-good-things-come-to-an-end-shutting-down-clear-linux-os/10716
18•todsacerdoti•30m ago•3 comments

How to write Rust in the Linux kernel: part 3

https://lwn.net/SubscriberLink/1026694/3413f4b43c862629/
27•chmaynard•1h ago•0 comments

Ccusage: A CLI tool for analyzing Claude Code usage from local JSONL files

https://github.com/ryoppippi/ccusage
14•kristianp•52m ago•4 comments

Silence Is a Commons by Ivan Illich (1983)

http://www.davidtinapple.com/illich/1983_silence_commons.html
59•entaloneralie•2h ago•9 comments

Broadcom to discontinue free Bitnami Helm charts

https://github.com/bitnami/charts/issues/35164
82•mmoogle•4h ago•45 comments

Wii U SDBoot1 Exploit “paid the beak”

https://consolebytes.com/wii-u-sdboot1-exploit-paid-the-beak/
63•sjuut•3h ago•7 comments

EPA says it will eliminate its scientific reseach arm

https://www.nytimes.com/2025/07/18/climate/epa-firings-scientific-research.html
61•anigbrowl•1h ago•25 comments

Multiplatform Matrix Multiplication Kernels

https://burn.dev/blog/sota-multiplatform-matmul/
44•homarp•4h ago•16 comments

lsr: ls with io_uring

https://rockorager.dev/log/lsr-ls-but-with-io-uring/
292•mpweiher•11h ago•151 comments

Valve confirms credit card companies pressured it to delist certain adult games

https://www.pcgamer.com/software/platforms/valve-confirms-credit-card-companies-pressured-it-to-delist-certain-adult-games-from-steam/
143•freedomben•8h ago•141 comments

Meta says it wont sign Europe AI agreement, calling it growth stunting overreach

https://www.cnbc.com/2025/07/18/meta-europe-ai-code.html
85•rntn•6h ago•119 comments

Trying Guix: A Nixer's impressions

https://tazj.in/blog/trying-guix
132•todsacerdoti•3d ago•38 comments

AI capex is so big that it's affecting economic statistics

https://paulkedrosky.com/honey-ai-capex-ate-the-economy/
181•throw0101c•4h ago•196 comments

Replication of Quantum Factorisation Records with a VIC-20, an Abacus, and a Dog

https://eprint.iacr.org/2025/1237
57•teddyh•5h ago•15 comments

Show HN: Molab, a cloud-hosted Marimo notebook workspace

https://molab.marimo.io/notebooks
61•akshayka•5h ago•8 comments

Mango Health (YC W24) Is Hiring

https://www.ycombinator.com/companies/mango-health/jobs/3bjIHus-founding-engineer
1•zachgitt•5h ago

Sage: An atomic bomb kicked off the biggest computing project in history

https://www.ibm.com/history/sage
12•rawgabbit•3d ago•0 comments

The year of peak might and magic

https://www.filfre.net/2025/07/the-year-of-peak-might-and-magic/
69•cybersoyuz•6h ago•35 comments

CP/M creator Gary Kildall's memoirs released as free download

https://spectrum.ieee.org/cpm-creator-gary-kildalls-memoirs-released-as-free-download
226•rbanffy•13h ago•118 comments

Show HN: I built library management app for those who outgrew spreadsheets

https://www.librari.io/
43•hmkoyan•4h ago•27 comments

Cancer DNA is detectable in blood years before diagnosis

https://www.sciencenews.org/article/cancer-tumor-dna-blood-test-screening
153•bookofjoe•5h ago•94 comments

A New Geometry for Einstein's Theory of Relativity

https://www.quantamagazine.org/a-new-geometry-for-einsteins-theory-of-relativity-20250716/
71•jandrewrogers•8h ago•1 comments

Show HN: Simulating autonomous drone formations

https://github.com/sushrut141/ketu
12•wanderinglight•3d ago•2 comments

How I keep up with AI progress

https://blog.nilenso.com/blog/2025/06/23/how-i-keep-up-with-ai-progress/
165•itzlambda•5h ago•85 comments

Benben: An audio player for the terminal, written in Common Lisp

https://chiselapp.com/user/MistressRemilia/repository/benben/home
46•trocado•3d ago•4 comments

Making a StringBuffer in C, and questioning my sanity

https://briandouglas.ie/string-buffer-c/
26•coneonthefloor•3d ago•15 comments

Hundred Rabbits – Low-tech living while sailing the world

https://100r.co/site/home.html
214•0xCaponte•4d ago•60 comments

How to Get Foreign Keys Horribly Wrong

https://hakibenita.com/django-foreign-keys
49•Bogdanp•3d ago•23 comments

When root meets immutable: OpenBSD chflags vs. log tampering

https://rsadowski.de/posts/2025/openbsd-immutable-system-logs/
126•todsacerdoti•15h ago•41 comments