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

Comments

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

Microsoft Exec Asks: Why Aren't More People Impressed with AI?

https://www.pcmag.com/news/microsoft-exec-asks-why-arent-more-people-impressed-with-ai
1•latexr•1m ago•0 comments

Bitoin won't recover until there's a resolution to quantum elephant in the room

1•r33b33•5m ago•0 comments

AI Models as Standalone P&Ls [Dario Amodei, Anthropic CEO]

https://philippdubach.com/2025/11/09/ai-models-as-standalone-pls/
1•7777777phil•6m ago•0 comments

Wavl Trees [pdf]

https://ics.uci.edu/~goodrich/teach/cs165/notes/WeakAVLTrees.pdf
1•fanf2•11m ago•0 comments

Show HN: AgentsKB – 3.3k verified answers to stop agent hallucinations

https://agentskb.com/
1•Cranot•12m ago•0 comments

D-Link warns of new RCE flaws in end-of-life DIR-878 routers

https://www.bleepingcomputer.com/news/security/d-link-warns-of-new-rce-flaws-in-end-of-life-dir-8...
1•01-_-•13m ago•0 comments

GitHub Actions cache size can now exceed 10 GB per repository

https://github.blog/changelog/2025-11-20-github-actions-cache-size-can-now-exceed-10-gb-per-repos...
1•meysamazad•15m ago•0 comments

New US rules say countries with diversity policies are infringing human rights

https://www.bbc.com/news/articles/cx24200d7y9o
1•osivertsson•15m ago•0 comments

Core message Ingo is conveying with this diagram

https://twitter.com/EstateIngoSwann/status/1991460118601388330
1•keepamovin•17m ago•0 comments

The first preserved Neanderthal nasal cavity in the human fossil record

https://www.pnas.org/doi/abs/10.1073/pnas.2426309122
2•janandonly•19m ago•0 comments

When Technology Crosses the Threshold Between Memory and Simulation

https://comuniq.xyz/post?t=542
1•01-_-•22m ago•0 comments

Nomor Telepon Halo-BCA (62 817.395.377)

1•Akirus•23m ago•0 comments

TeamViewer is experiencing issues – Management Console (MCO) not loading

https://status.teamviewer.com
1•taubek•24m ago•1 comments

I'm about to buy a $150 Apple trackpad for my Windows PC, please stop me

https://www.howtogeek.com/please-someone-stop-me-before-i-buy-this-150-trackpad/
1•dsego•28m ago•1 comments

As Lovable hits $200M ARR, its CEO credits staying in Europe for its success

https://techcrunch.com/2025/11/19/as-lovable-hits-200m-arr-its-ceo-credits-staying-in-europe-for-...
1•iamtech•30m ago•0 comments

AI Super Prompts

https://superprompts.dev/
1•klipitkas•31m ago•1 comments

Show HN: Low-Cost FPGA-Based Bit Error Rate Tester and Eye Diagram Analyzer

https://github.com/mmrdni/MBERT
1•aaaawwww•31m ago•0 comments

Deploying your own Cloudflare-style error page in your website

https://github.com/donlon/cloudflare-error-page
2•Donlon•32m ago•0 comments

Personal Security Checklist

https://digital-defense.io/
2•elashri•37m ago•0 comments

Money talks: the deep ties between Twitter and Saudi Arabia

https://www.theguardian.com/technology/2025/oct/09/twitter-saudi-arabia-deep-ties-elon-musk-princ...
1•INGELRII•39m ago•0 comments

Back to Basics: Let Denoising Generative Models Denoise

https://arxiv.org/abs/2511.13720
1•GaggiX•42m ago•0 comments

Show HN: Free Calculator for Outbound Sales Profitability

https://dealmayker.com/free-tools/free-outbound-sales-roi-calculator
1•aleksam•44m ago•0 comments

Comet for Android Is Out

https://play.google.com/store/apps/details?id=ai.perplexity.comet&hl=en
1•AHASIC•44m ago•1 comments

Michael Burry takes aim at Nvidia after its earnings blowout

https://www.businessinsider.com/big-short-michael-burry-nvidia-stock-earnings-ai-bubble-microchip...
2•MindBreaker2605•52m ago•0 comments

Quantum Tech That Helps Anyone Build a Smarter Stock Portfolio

https://soma.biz
2•Hellene•54m ago•0 comments

The most traveled Prime Minister

https://rodgercuddington.substack.com/p/britains-most-traveled-prime-minister
1•freespirt•55m ago•1 comments

The per-request isolation architecture of TinyKVM

https://fwsgonzo.medium.com/per-request-isolation-in-tinykvm-explained-080e84328ba4
1•fwsgonzo•56m ago•0 comments

Tracking domestication signals across populations of North American raccoons

https://frontiersinzoology.biomedcentral.com/articles/10.1186/s12983-025-00583-1
2•Kaibeezy•58m ago•0 comments

Superman Comic Found in Attic Sold for $9.12M

https://www.ha.com/c/press-release.zx?releaseId=5346&hero-pr-comicArt-results-superman-learnMore-...
1•HelloUsername•59m ago•0 comments

Stubborn Slider, Proactive Toggle and Naughty Button

https://chillcomponent.codlin.me/en/components/slider-stubborn/
1•xeonax•1h ago•1 comments