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

Commodore 64 floppy drive has the power to be a computer and runs BASIC

https://www.tomshardware.com/pc-components/cpus/commodore-64-floppy-drive-has-the-power-to-be-a-c...
2•rbanffy•1m ago•0 comments

Update: Finbley Adds an AI-Based Spending Analyst (Natural Language Queries)

https://www.finbley.com
1•mo_hackernews•2m ago•1 comments

LLM Problems Observed in Humans

https://embd.cc/llm-problems-observed-in-humans
1•js216•2m ago•0 comments

SanDisk terminates WD brands and introduces Optimus SSD range

https://www.igorslab.de/en/sandisk-ends-wd-brands-and-introduces-optimus-ssd-series/
2•speckx•3m ago•0 comments

Australia's Social Media Ban: Age Limits Won't Fix What's Wrong with Platforms

https://blog.mozilla.org/netpolicy/2025/12/19/australias-social-media-ban-why-age-limits-wont-fix...
1•PaulHoule•3m ago•0 comments

Show HN: Worldstream – Real-time stream of headlines from everywhere

https://worldstream.io
1•raj-shekhar•4m ago•0 comments

The launches and landings we're most excited about in 2026

https://arstechnica.com/space/2026/01/here-are-the-launches-and-landings-were-most-excited-about-...
1•rbanffy•4m ago•0 comments

New Year 2026: Fusion Updates from Helion and Commonwealth Fusion

1•ralfd•5m ago•0 comments

Ideas are cheap, execution is cheaper

https://davekiss.com/blog/ideas-are-cheap-execution-is-cheaper
1•vinhnx•5m ago•0 comments

Information Is Still Free

https://thehistoryoftheweb.com/information-is-still-free/
1•cdrnsf•6m ago•0 comments

US Job Openings Decline to Lowest Level in More Than a Year

https://www.bloomberg.com/news/articles/2026-01-07/us-job-openings-decline-to-lowest-level-in-mor...
12•toomuchtodo•6m ago•1 comments

AI pilots a free-flying robot inside the International Space Station

https://scienceclock.com/first-autonomous-ai-robot-flight-iss/
1•akg130522•6m ago•0 comments

Secure job offers through AI-powered interviews [video]

https://www.youtube.com/watch?v=IKUy-h9L5zg
1•snasan•6m ago•0 comments

AI means we don't have to deal with nerds dreaming up over-engineered solutions

https://twitter.com/garrett_makes/status/2008532223713022125
1•jonnycomputer•7m ago•3 comments

Wegmans grocery store uses biometric surveillance on shoppers

https://www.aol.com/articles/popular-grocery-store-chain-uses-130056099.html?_guc_consent_skip=17...
1•WaitWaitWha•7m ago•0 comments

Easily Accelerating Python with Rust via Claude Code

https://www.generativist.com/notes/2026/Jan/6/claude-code-python-and-rust-oh-my
1•generativist•7m ago•0 comments

Show HN: A Bento-based service for reliably streaming usage events into billing

https://twitter.com/tryflexprice/status/2008863789916274851
1•sudeepsd__•8m ago•0 comments

VR-based brain training for ADHD

https://medium.com/@6thMind/vr-based-brain-training-for-adhd-what-the-2025-research-reveals-about...
1•smanuel•9m ago•0 comments

US seizes Russian tanker – are we all going to die?

https://www.theguardian.com/world/live/2026/jan/07/europe-greenland-denmark-us-france-trade-weath...
3•zabzonk•9m ago•0 comments

Show HN: Career Control System – Roadmap in a repo for experienced developers

1•we_can•11m ago•0 comments

Proxying Flutter Traffic on Android with Claude

https://randywestergren.com/vibe-hacking-proxying-flutter-traffic-on-android-with-claude/
1•rwestergren•11m ago•0 comments

We might have been slower to abandon StackOverflow if it wasn't a toxic hellhole

https://www.pcloadletter.dev/blog/abandoning-stackoverflow/
6•ronbenton•11m ago•3 comments

AMD Ryzen chief teases return of older Zen 3 chips to fight soaring RAM prices

https://www.tomshardware.com/pc-components/cpus/amd-ryzen-chief-teases-return-of-older-zen-3-chip...
2•throwaway270925•13m ago•0 comments

Where good ideas come from (for coding agents)

https://sunilpai.dev/posts/seven-ways/
1•vinhnx•13m ago•0 comments

LeCun says Meta's new 29-year-old AI boss 'inexperienced', warns of staff exodus

https://www.cnbc.com/2026/01/05/ai-godfather-calls-meta-ai-boss-alexander-wang-inexperienced-.html
5•1vuio0pswjnm7•14m ago•1 comments

Supreme Court Increasingly Favors the Rich, Economists Say

https://www.nytimes.com/2026/01/05/us/politics/supreme-court-study-rich-poor.html
4•duxup•14m ago•2 comments

Nvidia could resurrect old GPUs to address shortages and high pricing

https://www.tomshardware.com/pc-components/gpus/nvidia-non-committal-on-plans-to-solve-gpu-pricin...
2•throwaway270925•14m ago•0 comments

Apt warning: Policy will reject signature within a year, see –audit for details

https://neilzone.co.uk/2026/01/dealing-with-apts-warning-policy-will-reject-signature-within-a-ye...
1•speckx•15m ago•0 comments

Ask HN: Is anyone aware of a LinkedIn mirror like xcancel.com for X?

2•danielfalbo•15m ago•1 comments

Show HN: Claude generated code for a 80s vector game engine in HTML+JS

https://eventhorizon-ek6.pages.dev
1•dterm•15m ago•0 comments