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

Adobe Photoshop 1.0 Source Code (1990)

https://computerhistory.org/blog/adobe-photoshop-source-code/
171•tosh•4d ago•44 comments

Instant database clones with PostgreSQL 18

https://boringsql.com/posts/instant-database-clones/
94•radimm•5h ago•13 comments

Postponed '60 Minutes' segment on Salvadoran prison is streamed by Canadian news

https://www.nbcnews.com/news/us-news/cbs-news-el-salvador-cecot-prison-sharyn-alfonsi-bari-weiss-...
40•duxup•36m ago•5 comments

Carnap – A formal logic framework for Haskell

https://carnap.io/
45•ravenical•3h ago•9 comments

Font with Built-In Syntax Highlighting (2024)

https://blog.glyphdrawing.club/font-with-built-in-syntax-highlighting/
27•california-og•2h ago•6 comments

Show HN: CineCLI – Browse and torrent movies directly from your terminal

https://github.com/eyeblech/cinecli
181•samsep10l•7h ago•69 comments

Snitch – A friendlier ss/netstat

https://github.com/karol-broda/snitch
213•karol-broda•12h ago•52 comments

It's Always TCP_NODELAY

https://brooker.co.za/blog/2024/05/09/nagle.html
354•eieio•15h ago•116 comments

The Illustrated Transformer

https://jalammar.github.io/illustrated-transformer/
407•auraham•17h ago•76 comments

Cecot – 60 Minutes

https://archive.org/details/insidececot
573•lawlessone•12h ago•55 comments

Ultrasound Cancer Treatment: Sound Waves Fight Tumors

https://spectrum.ieee.org/ultrasound-cancer-treatment
277•rbanffy•17h ago•82 comments

The Polyglot NixOS

https://x86.lol/generic/2025/12/19/polyglot.html
80•todsacerdoti•3d ago•22 comments

GLM-4.7: Advancing the Coding Capability

https://z.ai/blog/glm-4.7
363•pretext•18h ago•188 comments

Claude Code gets native LSP support

https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md
449•JamesSwift•21h ago•252 comments

10 years bootstrapped: €6.5M revenue with a team of 13

https://www.datocms.com/blog/a-look-back-at-2025
60•steffoz•5h ago•18 comments

NIST was 5 μs off UTC after last week's power cut

https://www.jeffgeerling.com/blog/2025/nist-was-5-μs-utc-after-last-weeks-power-cut
285•jtokoph•20h ago•127 comments

Our New Sam Audio Model Transforms Audio Editing

https://about.fb.com/news/2025/12/our-new-sam-audio-model-transforms-audio-editing/
117•ushakov•6d ago•44 comments

Executorch: On-device AI across mobile, embedded and edge for PyTorch

https://github.com/pytorch/executorch
3•klaussilveira•4d ago•0 comments

The Duodecimal Bulletin, Vol. 55, No. 1, Year 1209 [pdf]

https://dozenal.org/drupal/sites_bck/default/files/DuodecimalBulletinIssue551.pdf
45•susam•11h ago•11 comments

Debian adds LoongArch as officially supported architecture

https://lists.debian.org/debian-devel-announce/2025/12/msg00004.html
89•cbmuser•3d ago•21 comments

The Garbage Collection Handbook

https://gchandbook.org/index.html
227•andsoitis•17h ago•27 comments

Ask HN: What are the best engineering blogs with real-world depth?

81•nishilpatel•3h ago•47 comments

FCC Updates Covered List to Include Foreign UAS and UAS Critical Components [pdf]

https://docs.fcc.gov/public/attachments/DOC-416839A1.pdf
82•Espressosaurus•9h ago•62 comments

Flock Exposed Its AI-Powered Cameras to the Internet. We Tracked Ourselves

https://www.404media.co/flock-exposed-its-ai-powered-cameras-to-the-internet-we-tracked-ourselves/
637•chaps•20h ago•412 comments

Scaling LLMs to Larger Codebases

https://blog.kierangill.xyz/oversight-and-guidance
268•kierangill•21h ago•100 comments

Remove Black Color with Shaders

https://yuanchuan.dev/remove-black-color-with-shaders
38•surprisetalk•4d ago•10 comments

Solving the Problems of HBM-on-Logic

https://morethanmoore.substack.com/p/solving-the-problems-of-hbm-on-logic
4•zdw•5d ago•0 comments

A centennial look back at Edward Gorey's macabre art and guarded life

https://www.washingtonpost.com/books/2025/12/13/edward-gorey-centennial-gregory-hischak-review/
23•prismatic•6d ago•2 comments

Show HN: Python SDK – forecasting with foundation time-series and tabular models

https://github.com/S-FM/faim-python-client
26•ChernovAndrei•5d ago•8 comments

Universal Reasoning Model (53.8% pass 1 ARC1 and 16.0% ARC 2)

https://arxiv.org/abs/2512.14693
109•marojejian•18h ago•19 comments