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

Comments

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

CSS Grid Lanes

https://webkit.org/blog/17660/introducing-css-grid-lanes/
431•frizlab•8h ago•119 comments

Mistral OCR 3

https://mistral.ai/news/mistral-ocr-3
467•pember•1d ago•86 comments

Charles Proxy

https://www.charlesproxy.com/
8•handfuloflight•28m ago•0 comments

Garage – An S3 object store so reliable you can run it outside datacenters

https://garagehq.deuxfleurs.fr/
524•ibobev•14h ago•113 comments

Carolina Cloud – One third the cost of AWS for data science workloads

https://carolinacloud.io/
73•bojangleslover•5d ago•28 comments

Fuzix on a Raspberry Pi Pico

https://ewpratten.com/blog/fuzix-pi-pico
30•ewpratten•5d ago•1 comments

Android introduces $2-4 install fee and 10–20% cut for US external content links

https://support.google.com/googleplay/android-developer/answer/16470497?hl=en
63•radley•1h ago•24 comments

Gh-actions-lockfile: generate and verify lockfiles for GitHub Actions

https://gh-actions-lockfile.net
21•gjtorikian•3d ago•6 comments

TP-Link Tapo C200: Hardcoded Keys, Buffer Overflows and Privacy

https://www.evilsocket.net/2025/12/18/TP-Link-Tapo-C200-Hardcoded-Keys-Buffer-Overflows-and-Priva...
255•sibellavia•12h ago•70 comments

A better zip bomb (2019)

https://www.bamsoftware.com/hacks/zipbomb/
117•kekqqq•9h ago•41 comments

8-bit Boléro

https://linusakesson.net/music/bolero/index.php
213•Aissen•18h ago•36 comments

Graphite is joining Cursor

https://cursor.com/blog/graphite
211•fosterfriends•14h ago•221 comments

LLM Year in Review

https://karpathy.bearblog.dev/year-in-review-2025/
139•swyx•9h ago•36 comments

Brown/MIT shooting suspect found dead, officials say

https://www.washingtonpost.com/nation/2025/12/18/brown-university-shooting-person-of-interest/
133•anigbrowl•1d ago•164 comments

Build Your Own React

https://pomb.us/build-your-own-react/
55•howToTestFE•6h ago•4 comments

Rust's Block Pattern

https://notgull.net/block-pattern/
157•zdw•1d ago•72 comments

Qwen-Image-Layered: transparency and layer aware open diffusion model

https://huggingface.co/papers/2512.15603
89•dvrp•1d ago•15 comments

Show HN: TinyPDF – 3kb pdf library (70x smaller than jsPDF)

https://github.com/Lulzx/tinypdf
151•lulzx•1d ago•20 comments

Performance Hints (2023)

https://abseil.io/fast/hints.html
80•danlark1•13h ago•31 comments

The FreeBSD Foundation's Laptop Support and Usability Project

https://github.com/FreeBSDFoundation/proj-laptop
153•mikece•15h ago•56 comments

Believe the Checkbook

https://robertgreiner.com/believe-the-checkbook/
139•rg81•14h ago•60 comments

History LLMs: Models trained exclusively on pre-1913 texts

https://github.com/DGoettlich/history-llms
794•iamwil•1d ago•380 comments

Vm.overcommit_memory=2 is the right setting for servers

https://ariadne.space/2025/12/16/vmovercommitmemory-is-always-the-right.html
69•signa11•2d ago•108 comments

Amazon will allow ePub and PDF downloads for DRM-free eBooks

https://www.kdpcommunity.com/s/article/New-eBook-Download-Options-for-Readers-Coming-in-2026?lang...
575•captn3m0•20h ago•286 comments

The scariest boot loader code

http://miod.online.fr/software/openbsd/stories/boot_hppa.html
46•todsacerdoti•10h ago•4 comments

The pitfalls of partitioning Postgres yourself

https://hatchet.run/blog/postgres-partitioning
65•abelanger•3d ago•5 comments

GotaTun – Mullvad's WireGuard Implementation in Rust

https://mullvad.net/en/blog/announcing-gotatun-the-future-of-wireguard-at-mullvad-vpn
563•km•19h ago•121 comments

Reverse Engineering US Airline's PNR System and Accessing All Reservations

https://alexschapiro.com/security/vulnerability/2025/11/20/avelo-airline-reservation-api-vulnerab...
103•bearsyankees•12h ago•52 comments

Beginning January 2026, all ACM publications will be made open access

https://dl.acm.org/openaccess
1976•Kerrick•1d ago•233 comments

Buteyko Method

https://en.wikipedia.org/wiki/Buteyko_method
51•rzk•8h ago•33 comments