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.

Creepy Crawlies

https://people.kernel.org/monsieuricon/creepy-crawlies
771•zdw•1d ago•360 comments

Cores in space: The core memory module from a 1980 Spacelab computer

https://www.righto.com/2026/08/spacelab-core-memory.html
40•pwg•2h ago•8 comments

Haiku R1/beta6 has been released

https://www.haiku-os.org/news/2026-08-26_haiku_r1_beta6
210•metrofun•6h ago•58 comments

Continuous Diffusion Language Models (CDLM's)

https://sander.ai/2026/08/24/continuous-dlms.html
24•peter_d_sherman•1h ago•2 comments

NFC Energy-Harvesting PCB Business Card with an MCU

https://wilsonharper.net/projects/businesscard/
54•WilsonHarper•2d ago•4 comments

Why open source rocks – a new SM750 (Silicon Motion GPU) HDMI Driver

https://github.com/KodeMunkie/sm750hdmifb
49•SillyUsername•3h ago•25 comments

Sort branches by last commit date

https://ryangreenberg.com/til/git-branches-by-commit-date/
46•speckx•5d ago•13 comments

Coordination Headwind: How Organizations Are Like Slime Molds

https://komoroske.com/slime-mold/
107•rzk•6h ago•38 comments

Hacking IKEA Furniture

https://greenlightning.eu/diy/hacking-ikea-furniture/
239•greenlightning•10h ago•146 comments

Zig: Pointer Stability for ArrayLists

https://ziglang.org/devlog/2026/#2026-08-27
70•tosh•7h ago•30 comments

METR and Redwood Offer Holy %^ Postmortem of the HuggingFace Hack

https://thezvi.wordpress.com/2026/08/29/metr-and-redwood-offer-holy-postmortem-of-the-huggingface...
185•catbird•8h ago•126 comments

Dad’s Custom Atari Peripherals

https://www.goto10retro.com/p/dads-custom-atari-peripherals
77•rbanffy•3d ago•10 comments

Arbitrary code execution in QubesOS via copy-to-VM error reporting backchannel

https://www.qubes-os.org/news/2026/08/29/qsb-118/
190•vntok•13h ago•79 comments

Storm Summoner, a MIDI controller for effects pedals

https://kabaragoya.com/products/storm-summoner
22•peteforde•3d ago•8 comments

Omarchy: Any User Process Can Escalate to Root

https://0xcc.io/posts/omarchy-root-creds/
330•trap0xcc•6h ago•323 comments

Artie (YC S23) Is Hiring Technical AES

https://www.artie.com/careers?ashby_jid=e87b84d2-78b3-41a3-937a-47e83643cdf1
1•j-cheong•5h ago

European Commission Revives Push for Encryption Backdoors in ProtectEU Strategy

https://reclaimthenet.org/eu-protecteu-strategy-encryption-backdoor-law-enforcement
306•nickslaughter02•7h ago•123 comments

Electric rain can eat through metal

https://www.scientificamerican.com/article/electric-rain-can-eat-through-metal/
79•sohkamyung•3d ago•15 comments

Longest Straight Line Paths on Water or Land on the Earth (2018)

https://arxiv.org/abs/1804.07389
184•joebig•13h ago•55 comments

Startup Anti-Patterns

https://www.itamarnovick.com/intro-to-startup-anti-pattern-series/
32•rzk•6h ago•8 comments

Synchronisation and SMPTE timecode (time code)

https://www.philrees.co.uk/articles/timecode.htm
24•sublinear•2d ago•5 comments

Casey Muratori – The Root of the Root of All Evil – BSC 2026 [video]

https://www.youtube.com/watch?v=hpj6r6CjJf8
280•surprisetalk•3d ago•147 comments

Automating Immersive Reading

https://smoores.dev/post/automating_immersive_reading/
81•smoores•10h ago•29 comments

Europe's summer drought is so extreme that desertification is a growing threat

https://fortune.com/2026/08/29/europe-summer-drought-desertification-threat-rivers-fish/
218•Brajeshwar•7h ago•247 comments

What my dad taught me about AI coding in the 90s

https://askmike.org/articles/ai-coding-lessons-in-the-90s-from-my-dad/
118•askmike•6d ago•62 comments

Quest for the Eternal Dock – Lambdock

https://jointhefreeworld.org/blog/articles/gnu-linux/quest-for-eternal-dock/index.html
4•signa11•1d ago•0 comments

An implementation of Conway's Game of Life for Windows 3.1x and later

https://www.muppetlabs.com/~breadbox/software/windows.html
47•Bluestein•10h ago•11 comments

Hy4 preview

https://www.tencent.com/tencent-releases-and-open-sources-tencent-hy4-preview/
377•shenli3514•1d ago•238 comments

When fruit is scarce, these monkeys hunt animals

https://www.smithsonianmag.com/smart-news/when-fruit-is-scarce-these-monkeys-hunt-animals-the-beh...
54•cisc•1d ago•32 comments

Building my own network stack

https://blog.lyc8503.net/en/post/dn42-2-dnet/
91•uneven9434•12h ago•73 comments