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

FracturedJson

https://github.com/j-brooke/FracturedJson/wiki
262•PretzelFisch•3h ago•62 comments

Ask HN: Who is hiring? (January 2026)

29•whoishiring•38m ago•13 comments

10 years of personal finances in plain text files

https://sgoel.dev/posts/10-years-of-personal-finances-in-plain-text-files/
259•wrxd•5h ago•98 comments

39th Chaos Communication Congress Videos

https://media.ccc.de/b/congress/2025
198•Jommi•3h ago•23 comments

Standard Ebooks: Public Domain Day 2026 in Literature

https://standardebooks.org/blog/public-domain-day-2026
225•WithinReason•7h ago•40 comments

Assorted less(1) tips

https://blog.thechases.com/posts/assorted-less-tips/
64•todsacerdoti•4h ago•13 comments

HPV vaccination reduces oncogenic HPV16/18 prevalence from 16% to <1% in Denmark

https://www.eurosurveillance.org/content/10.2807/1560-7917.ES.2025.30.27.2400820
291•stared•6h ago•135 comments

Why users cannot create Issues directly

https://github.com/ghostty-org/ghostty/issues/3558
586•xpe•15h ago•211 comments

Show HN: Dealta – A game-theoretic decentralized trading protocol

https://github.com/orgs/Dealta-Foundation/repositories
33•kalenvale•4h ago•10 comments

Happy Public Domain Day 2026

https://publicdomainreview.org/blog/2026/01/public-domain-day-2026/
372•apetresc•14h ago•72 comments

Grok is enabling mass sexual harassment on Twitter

https://www.seangoedecke.com/grok-deepfakes/
20•savanaly•37m ago•1 comments

What You Need to Know Before Touching a Video File

https://gist.github.com/arch1t3cht/b5b9552633567fa7658deee5aec60453/
100•qbow883•5d ago•68 comments

A small collection of text-only websites

https://shkspr.mobi/blog/2025/12/a-small-collection-of-text-only-websites/
51•danielfalbo•5h ago•20 comments

A website to destroy all websites

https://henry.codes/writing/a-website-to-destroy-all-websites/
658•g0xA52A2A•20h ago•334 comments

Matz 2/2: The trajectory of Ruby's growth, Open-Source Software today etc.

https://en.kaigaiiju.ch/episodes/matz2
74•kibitan•6d ago•31 comments

Can I throw a C++ exception from a structured exception?

https://devblogs.microsoft.com/oldnewthing/20170728-00/?p=96706
44•birdculture•4d ago•9 comments

Show HN: Jsonic – Python JSON serialization that works

https://medium.com/dev-genius/jsonic-python-serialization-that-just-works-3b38d07c426d
16•orrbenyamini•6d ago•5 comments

ThingsBoard: Open-Source IoT Platform

https://github.com/thingsboard/thingsboard
3•pretext•5d ago•0 comments

Show HN: I built a clipboard tool to strip/keep specific formatting like Italics

https://custompaste.com
21•EvaWorld9•4h ago•8 comments

Parental Controls Aren't for Parents

https://beasthacker.com/til/parental-controls-arent-for-parents.html
152•beasthacker•2h ago•133 comments

FreeBSD: Home NAS, part 1 – configuring ZFS mirror (RAID1)

https://rtfm.co.ua/en/freebsd-home-nas-part-1-configuring-zfs-mirror-raid1/
98•todsacerdoti•9h ago•19 comments

IPv6 just turned 30 and still hasn't taken over the world

https://www.theregister.com/2025/12/31/ipv6_at_30/
28•Brajeshwar•1h ago•23 comments

The Netflix Simian Army (2011)

https://netflixtechblog.com/the-netflix-simian-army-16e57fbab116
10•rognjen•2h ago•9 comments

Cameras and Lenses (2020)

https://ciechanow.ski/cameras-and-lenses/
481•sebg•23h ago•53 comments

Can Bundler be as fast as uv?

https://tenderlovemaking.com/2025/12/29/can-bundler-be-as-fast-as-uv/
309•ibobev•19h ago•93 comments

Joseph Campbell Meets George Lucas – Part I (2015)

https://www.starwars.com/news/mythic-discovery-within-the-inner-reaches-of-outer-space-joseph-cam...
35•indigodaddy•1d ago•11 comments

One Number I Trust: Plain-Text Accounting for a Multi-Currency Household

https://lalitm.com/post/one-number-i-trust/
86•ayi•6h ago•58 comments

Contact the ISS

https://www.ariss.org/contact-the-iss.html
76•logikblok•5d ago•21 comments

Marmot – A distributed SQLite server with MySQL wire compatible interface

https://github.com/maxpert/marmot
149•zX41ZdbW•14h ago•29 comments

Linux is good now

https://www.pcgamer.com/software/linux/im-brave-enough-to-say-it-linux-is-good-now-and-if-you-wan...
983•Vinnl•20h ago•797 comments