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.

Leaving Mozilla

https://blog.unitedheroes.net/5751
80•martey•2h ago•12 comments

Shepherd's Dog: A Game by the Most Dangerous AI Model

https://koenvangilst.nl/lab/claude-fable-shepherds-dog
55•vnglst•2h ago•43 comments

Statement on US government directive to suspend access to Fable 5 and Mythos 5

https://www.anthropic.com/news/fable-mythos-access
2097•Dylan1312•7h ago•1532 comments

Electric motors with no rare earths

https://www.renaultgroup.com/en/magazine/energy-and-powertrains/all-about-electric-motors-with-no...
412•bestouff•10h ago•109 comments

There is a shadow hanging over this Fable thing

https://12gramsofcarbon.com/p/tech-things-there-is-a-massive-shadow
196•theahura•3h ago•173 comments

CRISPR tech selectively shreds cancer cells, including "undruggable" cancers

https://innovativegenomics.org/news/crispr-technique-selectively-shreds-cancer-cells/
802•gmays•17h ago•190 comments

Open source AI must win

https://opensourceaimustwin.com/?share=v2
819•vednig•6h ago•254 comments

Show HN: Putt.day a daily mini golf game

https://putt.day/
154•ellg•9h ago•71 comments

Twenty One Zero-Days in FFmpeg

https://depthfirst.com/research/21-zero-days-in-ffmpeg
188•redbell•10h ago•117 comments

Israeli firm BlackCore suspected of meddling in New York and Scotland votes

https://www.reuters.com/world/israeli-firm-blackcore-also-suspected-meddling-nyc-scotland-votes-f...
30•pera•41m ago•8 comments

How to setup a local coding agent on macOS

https://ikyle.me/blog/2026/how-to-setup-a-local-coding-agent-on-macos
356•kkm•14h ago•86 comments

The computer science degree isn’t dead

https://spectrum.ieee.org/computer-science-degree-isnt-dead
74•jnord•3d ago•57 comments

On CPU Physics and CPU Cycles

https://6it.dev/blog/on-cpu-physics-and-cpu-cycles-80730
33•signa11•3h ago•5 comments

Swift at Apple: Migrating the TrueType hinting interpreter

https://www.swift.org/blog/migrating-truetype-hinting-to-swift/
192•DASD•12h ago•86 comments

Launch HN: BitBoard (YC P25) – Analytics Workspace for Agents

https://bitboard.work/
43•arcb•15h ago•21 comments

Malware developers added nuclear and biological weapons text to to their spyware

https://twitter.com/jsrailton/status/2064661778978533571
377•marc__1•1d ago•217 comments

H.R. 6028 would fundamentally change the U.S. Copyright Office

https://www.eff.org/deeplinks/2026/06/congress-just-rushed-through-disastrous-copyright-office-ov...
208•Cider9986•2d ago•63 comments

Show HN: Lightweight Task queue on Erlang/OTP, SQLite-backed, no overengineering

https://github.com/entGriff/ezra
27•ent1c3d•2d ago•5 comments

Using the Epson Perfection V39 II Scanner on Ubuntu

https://patches.joao.town/using-epson-perfection-v39ii-scanner-ubuntu/
5•joaopalmeiro•1d ago•0 comments

Pirates, a naval warfare game inspired by Sid Meier's Pirates

https://piwodlaiwo.github.io/pirates/
250•iweczek•15h ago•78 comments

Tectonic: A modernized, complete, self-contained TeX/LaTeX engine

https://tectonic-typesetting.github.io/en-US/
48•maxloh•3d ago•11 comments

The Alchemist of Flesh: The Man Who Turned Humans into Stone(2025)

https://medium.com/@Arcaarcana/the-extraordinary-story-of-girolamo-segato-03d8dae30758
6•ofalkaed•2d ago•0 comments

The Future of wasi-gfx and wasi:webgpu

https://wasi-gfx.dev/blog/posts/future-of-wasi-gfx/
21•mendyberger•3d ago•5 comments

Show HN: Skill for your agent to visualize your gbrain and Obsidian

https://github.com/vladignatyev/brain-map-skill
3•v_ignatyev•1h ago•0 comments

Slightly reducing the sloppiness of AI generated front end

https://envs.net/~volpe/blog/posts/reduce-slop.html
191•FergusArgyll•17h ago•119 comments

Automating Myself Out of Development

https://www.thoughtfultechnologist.com/p/automating-myself-out-of-development
12•nisabek•3d ago•7 comments

Palantir loses legal challenge against Swiss investigative magazine

https://www.ft.com/content/7ffcace7-9dc0-4e7e-9912-895ac073f979
318•sschueller•11h ago•63 comments

TycoonLE: A Jax reinforcement learning environment for long-horizon planning

https://github.com/vrtnis/tycoon-learning-environment
12•vrtnis•6h ago•1 comments

A key remapping daemon for Linux

https://github.com/rvaiya/keyd
46•joooscha•2d ago•21 comments

If you are asking for human attention, demonstrate human effort

https://tombedor.dev/human-attention-and-human-effort/
1581•jjfoooo4•1d ago•471 comments