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•11mo ago

Comments

Neywiny•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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•11mo 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";
  }

ChatGPT Images 2.0

https://openai.com/index/introducing-chatgpt-images-2-0/
109•wahnfrieden•3h ago•108 comments

The Vercel breach: OAuth attack exposes risk in platform environment variables

https://www.trendmicro.com/en_us/research/26/d/vercel-breach-oauth-supply-chain.html
221•queenelvis•5h ago•85 comments

Britannica11.org – a structured edition of the 1911 Encyclopædia Britannica

https://britannica11.org/
174•ahaspel•4h ago•80 comments

Stephen's Sausage Roll remains one of the most influential puzzle games

https://thinkygames.com/features/10-years-of-grilling-stephens-sausage-roll-remains-one-of-the-mo...
74•tobr•3d ago•36 comments

Framework Laptop 13 Pro

https://frame.work/laptop13pro
710•Trollmann•4h ago•408 comments

Cal.diy: open-source community edition of cal.com

https://github.com/calcom/cal.diy
117•petecooper•4h ago•34 comments

Laws of Software Engineering

https://lawsofsoftwareengineering.com
768•milanm081•11h ago•386 comments

A Periodic Map of Cheese

https://cheesemap.netlify.app/
148•sfrechtling•5h ago•64 comments

Edit store price tags using Flipper Zero

https://github.com/i12bp8/TagTinker
242•trueduke•2d ago•251 comments

Zindex – Diagram Infrastructure for Agents

https://zindex.ai/
13•_ben_•2h ago•5 comments

My practitioner view of program analysis

https://sawyer.dev/posts/practitioner-program-analysis/
22•evakhoury•1d ago•0 comments

Changes to GitHub Copilot individual plans

https://github.blog/news-insights/company-news/changes-to-github-copilot-individual-plans/
237•zorrn•1d ago•41 comments

Theseus, a Static Windows Emulator

https://neugierig.org/software/blog/2026/04/theseus.html
59•zdw•1d ago•6 comments

I don't want your PRs anymore

https://dpc.pw/posts/i-dont-want-your-prs-anymore/
148•speckx•2h ago•86 comments

Show HN: GoModel – an open-source AI gateway in Go

https://github.com/ENTERPILOT/GOModel/
151•santiago-pl•8h ago•56 comments

In the UK, EVs are cheaper than petrol cars, thanks to Chinese competition

https://electrek.co/2026/04/18/in-the-uk-evs-are-cheaper-than-petrol-cars-thanks-to-chinese-compe...
67•breve•2d ago•40 comments

Trellis AI (YC W24) Is hiring engineers to build self-improving agents

https://www.ycombinator.com/companies/trellis-ai/jobs/SvzJaTH-member-of-technical-staff-product-e...
1•macklinkachorn•5h ago

Running a Minecraft Server and More on a 1960s Univac Computer

https://farlow.dev/2026/04/17/running-a-minecraft-server-and-more-on-a-1960s-univac-computer
174•brilee•3d ago•28 comments

Show HN: Backlit Keyboard API for Python

https://github.com/itsmeadarsh2008/backlit-kbd
6•itsmeadarsh•2d ago•1 comments

California has more money than projected after admin miscalculated state budget

https://www.kcra.com/article/california-more-money-than-projected-newsom-miscalculated-budget/710...
71•littlexsparkee•1h ago•34 comments

Show HN: VidStudio, a browser based video editor that doesn't upload your files

https://vidstudio.app/video-editor
227•kolx•10h ago•78 comments

Fusion Power Plant Simulator

https://www.fusionenergybase.com/fusion-power-plant-simulator
130•sam•8h ago•71 comments

Modern Front end Complexity: essential or accidental?

https://binaryigor.com/modern-frontend-complexity.html
54•gsky•2d ago•38 comments

Meta capturing employee mouse movements, keystrokes for AI training data

https://www.reuters.com/sustainability/boards-policy-regulation/meta-start-capturing-employee-mou...
180•dlx•4h ago•120 comments

A type-safe, realtime collaborative Graph Database in a CRDT

https://codemix.com/graph
138•phpnode•11h ago•42 comments

Ibuilt a tiny Unix‑like 'OS' with shell and filesystem for Arduino UNO (2KB RAM)

https://github.com/Arc1011/KernelUNO
54•Arc1011•5h ago•12 comments

MNT Reform is an open hardware laptop, designed and assembled in Germany

http://mnt.stanleylieber.com/reform/
257•speckx•1d ago•96 comments

Show HN: Mediator.ai – Using Nash bargaining and LLMs to systematize fairness

https://mediator.ai/
142•sanity•1d ago•73 comments

Kasane: New drop-in Kakoune front end with GPU rendering and WASM Plugins

https://github.com/Yus314/kasane
39•nsagent•6h ago•5 comments

Colorado River disappeared record for 5M years: now we know where it was

https://phys.org/news/2026-04-colorado-river-geological-million-years.html
42•wglb•1d ago•8 comments