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

Translating Cave Story into Classical Latin with Gemini

https://www.semilin.dev/blog/doukutsu-translator
1•semilin•4m ago•0 comments

Show HN: I Made a Gamma Clone with 1 Prompt

https://prompt-to-ppt.lovable.app/
1•nsemikey•4m ago•1 comments

Cool project, will you maintain it?

https://www.pcloadletter.dev/blog/cool-project/
1•ronbenton•5m ago•0 comments

The State of LLMs 2025: Progress, Problems, and Predictions

https://magazine.sebastianraschka.com/p/state-of-llms-2025
1•nsainsbury•9m ago•0 comments

The Intelligent Universe: AI, ET, and the Emerging Mind of the Cosmos

https://www.setileague.org/reviews/intellig.htm
1•teleforce•13m ago•0 comments

Physics of Language Models: How to Build Versatile Pretrain Playgrounds [video]

https://www.youtube.com/watch?v=x3G8knjPDbM
1•gmays•15m ago•0 comments

Ask HN: Have you been falsely accused of AI-generated content?

3•bmaupin•16m ago•0 comments

What Becomes Valuable When AI Makes Creative Work Easy

https://every.to/p/what-becomes-valuable-when-ai-makes-creative-work-easy?p=c0fe0e66aa5670c292b26...
2•herbertl•16m ago•0 comments

I built my dream terminal based task manager

https://github.com/fashton28/silo
2•fashton28•16m ago•1 comments

Scorg Marketplace – Player-to-Player Trading for Star Citizen Items

1•legitcoders•18m ago•0 comments

Show HN: I built a Music-to-Video API

https://peakmv.com
2•gautamaj•20m ago•0 comments

Researchers spot Saturn-sized planet in the "Einstein desert"

https://arstechnica.com/science/2026/01/researchers-spot-saturn-sized-planet-in-the-einstein-desert/
2•pseudolus•22m ago•0 comments

Show HN: PPTX Native AI Slides

https://www.textdeck.com/home
1•andventures•23m ago•0 comments

Self-driving cars could prevent over 1M injuries across the US by 2035

https://techxplore.com/news/2026-01-cars-million-road-injuries.html
2•geox•26m ago•0 comments

On the quantum mechanics of entropic forces

https://arxiv.org/abs/2502.17575
1•kaycebasques•29m ago•0 comments

Ask HN: Are there any antifeature-free power tools you can still buy new?

3•josephcsible•31m ago•1 comments

AI Personas and Dolls

https://stephen.bochinski.dev/blog/2026/01/02/ai-personas/
2•sbochins•35m ago•0 comments

Obesity as a Behavioral Addiction

https://www.academia.edu/2997-9196/2/3/10.20935/MHealthWellB7880
3•red369•38m ago•2 comments

1964 New York World's Fair

https://en.wikipedia.org/wiki/1964_New_York_World%27s_Fair
2•teleforce•46m ago•0 comments

Show HN: Black Box QA testing system to automate QA process

https://www.rocksmith.ai/
1•orangeAvocad0•47m ago•0 comments

KGGen: Extracting Knowledge Graphs from Plain Text with Language Models

https://arxiv.org/abs/2502.09956
3•delichon•52m ago•0 comments

Show HN: Endless, a easily deployable and scalable social media

https://github.com/XS-Xspert-Software/Social-Media
1•thegoodduck•52m ago•0 comments

Breakfast menu prices are likely to see the biggest increase from food inflation

https://londonlovesbusiness.com/breakfast-menu-prices-are-likely-to-see-the-biggest-increase-from...
1•teleforce•52m ago•0 comments

The Force Is with Cristal Beer

https://en.wikipedia.org/wiki/The_Force_is_with_Cristal_Beer
3•handfuloflight•55m ago•0 comments

Tech Startups Are Handing Out Free Nicotine Pouches to Boost Productivity

https://www.wsj.com/tech/tech-startups-are-handing-out-free-nicotine-pouches-to-boost-productivit...
1•croes•58m ago•1 comments

Show HN: Shipping Without Judgment

https://dantelex.com/blog/shipping-judgement
3•lexokoh•1h ago•0 comments

ADF Opus: open, browse, and manage Amiga .ADF disk-images natively

https://github.com/chironb/ADFOpus2025
1•doener•1h ago•0 comments

Minimig RTG Magic [video]

https://www.youtube.com/watch?v=DBO9sD6EYS4
1•doener•1h ago•0 comments

GNU Ddrescue 1.30 Orders of Magnitude Better Working on Drives with a Dead Head

https://www.phoronix.com/news/GNU-ddrescue-1.30
5•Qem•1h ago•0 comments

Riot Games's League of Legends login issues due to expired SSL certificate

https://old.reddit.com/r/leagueoflegends/comments/1q40aen/comment/nxpij3c/
3•dossy•1h ago•1 comments