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

Δ-Mem: Efficient Online Memory for Large Language Models

https://arxiv.org/abs/2605.12357
32•44za12•1h ago•7 comments

Futhark by Example

https://futhark-lang.org/examples.html
17•tosh•1h ago•2 comments

Project Gutenberg – keeps getting better

https://www.gutenberg.org/
960•JSeiko•18h ago•202 comments

We've made the world too complicated

https://user8.bearblog.dev/the-world-is-too-complicated/
21•James72689•2h ago•15 comments

Frontier AI has broken the open CTF format

https://kabir.au/blog/the-ctf-scene-is-dead
153•frays•4h ago•133 comments

I believe there are entire companies right now under AI psychosis

https://twitter.com/mitchellh/status/2055380239711457578
1409•reasonableklout•14h ago•705 comments

Ploopy Bean: a trackpoint for every computer

https://ploopy.co/shop/bean-pointing-stick/
101•jibcage•3d ago•46 comments

The bird eye was pushed to an evolutionary extreme

https://www.quantamagazine.org/how-the-bird-eye-was-pushed-to-an-evolutionary-extreme-20260513/
124•sohkamyung•2d ago•42 comments

Additive Blending on the Nintendo 64

https://phoboslab.org/log/2026/05/n64-additive-blending
121•ibobev•20h ago•11 comments

EMiX: Emulating Beyond Single-FPGA Limits

https://arxiv.org/abs/2604.27012
13•PaulHoule•2d ago•1 comments

Gaining control of every projector and camera on campus

https://www.edna.land/blogs/posts/scanning/
33•ednaordinary•2d ago•7 comments

SQL patterns I use to catch transaction fraud

https://analytics.fixelsmith.com/posts/sql-fraud-patterns/
246•redbell•11h ago•80 comments

The main thing about P2P meth is that there's so much of it (2021)

https://dynomight.net/p2p-meth/
130•tomjakubowski•11h ago•155 comments

A 0-click exploit chain for the Pixel 10

https://projectzero.google/2026/05/pixel-10-exploit.html
386•happyhardcore•21h ago•206 comments

Naturally Occurring Quasicrystals

https://johncarlosbaez.wordpress.com/2026/05/14/naturally-occurring-quasicrystals/
103•lukeplato•1d ago•9 comments

Where to buy a non-Apple, non-Google smartphone

https://www.theregister.com/on-prem/2026/05/01/where-to-buy-a-non-apple-non-google-smartphone/521...
35•_____k•2h ago•11 comments

How to Write to SSDs [pdf]

https://www.vldb.org/pvldb/vol19/p1469-lee.pdf
122•matt_d•12h ago•16 comments

Orthrus-Qwen3: up to 7.8×tokens/forward on Qwen3, identical output distribution

https://github.com/chiennv2000/orthrus
104•FranckDernoncou•12h ago•15 comments

England Runestones

https://en.wikipedia.org/wiki/England_runestones
53•cl3misch•3d ago•21 comments

Nearly 50 Years Later, WKRP in Cincinnati Becomes a Real Radio Station

https://www.openculture.com/2026/05/nearly-50-years-later-wkrp-in-cincinnati-becomes-a-real-radio...
6•bookofjoe•3d ago•2 comments

The sigmoids won't save you

https://www.astralcodexten.com/p/the-sigmoids-wont-save-you
211•Tomte•1d ago•211 comments

Bill to block publishers from killing online games advances in California

https://arstechnica.com/gaming/2026/05/bill-to-keep-online-games-playable-clears-key-hurdle-in-ca...
494•Lihh27•15h ago•320 comments

Charity – Categorical programming language (1998)

https://github.com/mietek/charity-lang/blob/master/doc/README.md
6•matteodelabre•3d ago•0 comments

I Bought a “Junk” PSP From Japan

https://gardinerbryant.com/i-bought-a-junk-psp-from-japan-heres-how-it-went/
73•Kate0CoolLibby•3d ago•30 comments

Show HN: Epiq – Distributed Git based issue tracker TUI

https://ljtn.github.io/epiq/
61•jolaflow•10h ago•25 comments

I designed a nibble-oriented CPU in Verilog to build a scientific calculator

https://github.com/gdevic/FPGA-Calculator
105•gdevic•17h ago•34 comments

Image-blaster: Creates 3D environments, SFX, and meshes from a single image

https://github.com/neilsonnn/image-blaster
164•MattRogish•19h ago•31 comments

ESP-EEG is an affordable 8-channel biosensing board

https://www.autodidacts.io/cerelog-esp-eeg-affordable-openbci-like-board/
51•surprisetalk•2d ago•14 comments

Research on mildew contamination affecting the sound quality of analog tapes

https://www.nature.com/articles/s40494-026-02592-7
24•crousto•1d ago•1 comments

Show HN: Watch a neural net learn to play Snake

https://ppo.gradexp.xyz/
161•c1b•1d ago•38 comments