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•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();
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.

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

New accessibility features powered by Apple Intelligence

https://www.apple.com/newsroom/2026/05/apple-unveils-new-accessibility-features-and-updates-with-...
183•interpol_p•2h ago•78 comments

OpenBSD 7.9 Released

https://www.openbsd.org/79.html
79•bradley_taunt•59m ago•16 comments

Gaussian Splat of a Strawberry

https://superspl.at/scene/84df8849
231•danybittel•3h ago•88 comments

I Found Ultra-Pure Quantum Crystals in an Abandoned Mine in the Atacama Desert

https://medium.com/@breid.at/ultra-pure-quantum-crystals-from-an-abandoned-mine-in-a-mysterious-d...
151•vi_sextus_vi•2d ago•38 comments

Nim-Presto – REST API Framework for Nim Language

https://github.com/status-im/nim-presto
29•TheWiggles•2d ago•2 comments

Photo GIMP – A Patch for GIMP 3 for Photoshop Users

https://github.com/Diolinux/PhotoGIMP
116•SockThief•2d ago•80 comments

Mini Shai-Hulud Strikes Again: 314 npm Packages Compromised

https://safedep.io/mini-shai-hulud-strikes-again-314-npm-packages-compromised/
197•theanonymousone•9h ago•115 comments

Polypad

https://polypad.amplify.com/
138•ivank•2d ago•13 comments

Peter Neumann has died

https://www.tuhs.org/pipermail/tuhs/2026-May/033748.html
218•pabs3•10h ago•19 comments

Anthropic Is Preparing for IPO and We Should Be Worried

https://www.vincentschmalbach.com/anthropic-ipo-developers-should-be-worried-v2/
27•vincent_s•40m ago•25 comments

Hanoi's humble beer glass and the memory of a nation

https://sundaylongread.com/2026/05/15/hanois-humble-beer-glass-and-the-memory-of-a-nation/
8•NaOH•20h ago•0 comments

An Apple (II) for Teacher

https://technicshistory.com/2026/05/19/an-apple-ii-for-teacher/
11•cfmcdonald•13h ago•1 comments

Colonization of Venus

https://en.wikipedia.org/wiki/Colonization_of_Venus
42•simonebrunozzi•1h ago•21 comments

Click (2016)

https://clickclickclick.click/
335•andrewzeno•15h ago•84 comments

Kv4p HT – A homebrew 1W radio (VHF or UHF) that plugs into an Android phone

https://www.kv4p.com/
121•krupan•2d ago•46 comments

Cursor Introduces Composer 2.5

https://cursor.com/blog/composer-2-5
203•asar•20h ago•160 comments

Anthropic acquires Stainless

https://www.anthropic.com/news/anthropic-acquires-stainless
489•tomeraberbach•21h ago•346 comments

The lasting influence of Netscape Time

https://thehistoryoftheweb.com/the-lasting-influence-of-netscape-time/
68•zdw•2d ago•13 comments

Energy return in running shoes explained (2025)

https://runrepeat.com/guides/energy-return-in-running-shoes
35•jstrieb•1d ago•37 comments

PyTorch Landscape

https://pytorch.landscape2.io
64•salamo•9h ago•17 comments

1024000^2 Blocks, 2B2T Minecraft Server World Download Project, and Discoveries

https://github.com/2b2tplace/1m_release
162•exploraz•23h ago•101 comments

The last six months in LLMs in five minutes

https://simonwillison.net/2026/May/19/5-minute-llms/
560•yakkomajuri•12h ago•461 comments

We let AIs run radio stations

https://andonlabs.com/blog/andon-fm
308•lukaspetersson•19h ago•230 comments

Regex Chess: A 2-ply minimax chess engine in 84,688 regular expressions

https://nicholas.carlini.com/writing/2025/regex-chess.html
155•surprisetalk•4d ago•39 comments

Show HN: Number Gacha, a gacha game distilled to its essence

https://isabisabel.com/gacha/
196•babel16•5d ago•94 comments

CISA Admin Leaked AWS GovCloud Keys on GitHub

https://krebsonsecurity.com/2026/05/cisa-admin-leaked-aws-govcloud-keys-on-github/
25•LelouBil•6h ago•0 comments

Make ZIP files smaller with ZIP Shrinker

https://evanhahn.com/make-zip-files-smaller-with-zip-shrinker/
51•zdw•2d ago•36 comments

Hyperpolyglot Lisp: Common Lisp, Racket, Clojure, Emacs Lisp

https://hyperpolyglot.org/lisp
172•veqq•18h ago•42 comments

Show HN: Hsrs – Type-Safe Haskell Bindings Generator for Rust

https://github.com/harmont-dev/hsrs
45•suis_siva•10h ago•3 comments

Pope Leo XIV’s first encyclical Magnifica humanitas to be published May 25

https://www.vaticannews.va/en/pope/news/2026-05/pope-leo-xiv-first-encyclical-magnifica-humanitas...
262•cucho•14h ago•182 comments