frontpage.
newsnewestaskshowjobs

Open Source @Github

fp.

Open in hackernews

Understanding Java's Asynchronous Journey

https://amritpandey.io/understanding-javas-asynchronous-journey/
17•hardasspunk•1y ago

Comments

Neywiny•1y 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•1y 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•1y 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•1y 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•1y 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•1y 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•1y 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();
AtlasBarfed•1y 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•1y 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";
  }
wpollock•1y 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.

Show HN: CATT 0.2.1: Test your agent/service against a Muse/Instict-alike, in CI

https://github.com/Coverage-Cat/consumer-agent-testing-tool
1•botacode•30s ago•0 comments

Rule 30: one black cell

https://www.wolframcollatzmahler.com/rule30/index.html
1•amichail•2m ago•0 comments

Open call for guest investigators in the life sciences

https://www.anthropic.com/news/open-call-guest-investigators-life-sciences
1•surprisetalk•3m ago•0 comments

Sony Exits UHD Blu-ray Player Market as Pull Back from Physical Media Continues

https://www.pushsquare.com/news/2026/10/sony-exits-uhd-blu-ray-player-market-as-pull-back-from-ph...
1•throw0101c•4m ago•0 comments

100% Reproducible OpenWrt SNAPSHOTs

https://aparcar.org/100-reproducible-openwrt/
1•aparcar•5m ago•0 comments

Liquid AI launches sub-20ms latency stack

https://www.liquid.ai/blog/low-latency
1•pember•7m ago•2 comments

Show HN: MarketMee – Builds marketing material from every push to GitHub

https://marketmee.app
1•adeiji1•8m ago•0 comments

The $300k Competition to Hijack AI Agents

https://www.aiengineering.report/p/inside-the-300k-competition-to-hijack
1•waprin•9m ago•0 comments

FBI sent a letter to MLK to try to convince him to kill himself

https://www.vox.com/xpress/2014/11/12/7204453/martin-luther-king-fbi-letter
4•handfuloflight•10m ago•0 comments

Show HN: Stumble Upon for AI News

https://ainews247.org/
2•computerex•11m ago•0 comments

Divine D. MVP

1•dawndrums•11m ago•0 comments

I'm Not Doing 996

https://www.elenaverna.com/p/im-not-doing-996
2•simonebrunozzi•13m ago•0 comments

The Perl and Raku Foundation by the Numbers

https://www.olafalders.com/2026/10/22/the-perl-and-raku-foundation-by-the-numbers/
1•oalders•13m ago•0 comments

Show HN: CNET – Complex-valued neural networks from scratch in C++/CUDA

https://github.com/crasmarum/CNet
2•almaya•13m ago•0 comments

The cult of the iPhone mini is alive and thriving

https://www.fastcompany.com/91625181/the-cult-of-the-iphone-mini-is-alive-and-thriving
1•layer8•14m ago•0 comments

Next Concept Modeling: Fast, Parallel Coarse-to-Fine Text Generation

https://github.com/HazyResearch/ncm
1•droidjj•15m ago•0 comments

Show HN: whytime: time(1) that tells you where the wall-clock time went

https://github.com/Arinerron/whytime
1•Arinerron•16m ago•0 comments

OpenClaw creator says he spent $10M in tokens last month

https://www.theregister.com/ai-and-ml/2026/10/21/openclaw-creator-says-he-spent-10-million-in-tok...
6•gmays•23m ago•2 comments

Thoughts on AI in game development (from the trenches)

https://www.reddit.com/r/Games/comments/1xcr1au/thoughts_on_ai_in_game_development_from_the/
1•minimaxir•23m ago•0 comments

Memory Safe PHP

https://mbrock.github.io/filnix/php-on-filc/
1•pizlonator•27m ago•0 comments

Pangram 4.1 Model Card

https://www.pangram.com/research/model-card/pangram-4-1
1•Nition•29m ago•1 comments

True Depth Makes Crossing Boundaries Safe from Confident Ignorance

https://civicpivot.blogspot.com/2026/10/anchored-generalism-what-depth-makes.html
1•civicpivot•31m ago•0 comments

Coordinated Vulnerability Disclosure: How to do it and why it matters

https://coordinated-vulnerability-disclosure.github.io/en-us/
1•jph•31m ago•1 comments

WindowINK – An offline-first, mobile-first digital signage solution

https://www.windowink.com/
1•desvides•34m ago•0 comments

US banks are blocking third-party AI agents access to customer accounts

https://www.reuters.com/legal/government/us-banks-detect-unauthorized-ai-agents-customer-accounts...
5•champagnepapi•35m ago•2 comments

Meta to Pay Zuckerberg's CA Wealth Tax

https://seekingalpha.com/news/4655678-meta-approves-class-c-share-structure-strikes-deal-to-retai...
5•bigwheels•35m ago•3 comments

How does Fable 5.1 hide messages in images?

https://www.lesswrong.com/posts/WHEQps5PK8LrrcTAb/how-does-fable-5-1-hide-messages-in-images
3•gmays•37m ago•0 comments

Railpass

https://train.samismith.com/
7•CharlesW•40m ago•3 comments

Show HN: Hexal – Modal text editor with feature parity with Helix, Lua plugins

https://hexal.pages.dev/
2•whatever990•42m ago•0 comments

Claudopus vs. Astralisk

https://kbr.is-a.dev/claudopus-vs-astralisk/
1•kbr-•45m ago•0 comments