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

Comments

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

How I use Claude Code: Separation of planning and execution

https://boristane.com/blog/how-i-use-claude-code/
164•vinhnx•2h ago•97 comments

Palantir's secret weapon isn't AI – it's Ontology. An open-source deep dive

https://github.com/Leading-AI-IO/palantir-ontology-strategy
17•leading-AI•49m ago•8 comments

Show HN: Llama 3.1 70B on a single RTX 3090 via NVMe-to-GPU bypassing the CPU

https://github.com/xaskasdf/ntransformer
121•xaskasdf•6h ago•28 comments

A Botnet Accidentally Destroyed I2P

https://www.sambent.com/a-botnet-accidentally-destroyed-i2p-the-full-story/
23•Cider9986•2h ago•6 comments

Evidence of the bouba-kiki effect in naïve baby chicks

https://www.science.org/doi/10.1126/science.adq7188
80•suddenlybananas•5h ago•23 comments

Parse, Don't Validate and Type-Driven Design in Rust

https://www.harudagondi.space/blog/parse-dont-validate-and-type-driven-design-in-rust/
135•todsacerdoti•7h ago•38 comments

How far back in time can you understand English?

https://www.deadlanguagesociety.com/p/how-far-back-in-time-understand-english
385•spzb•3d ago•227 comments

zclaw: personal AI assistant in under 888 KB, running on an ESP32

https://github.com/tnm/zclaw
113•tosh•14h ago•59 comments

Scientists discover recent tectonic activity on the moon

https://phys.org/news/2026-02-scientists-tectonic-moon.html
14•bookmtn•4d ago•0 comments

Why every AI video tool feels broke

https://www.openslop.ai/blog/why-every-ai-video-tool-feels-broken
5•umairnadeem123•1h ago•0 comments

The Internet Is Becoming a Dark Forest – and AI Is the Hunter

https://opennhp.org/blog/the-internet-is-becoming-a-dark-forest.html
8•windcbf•2h ago•5 comments

CXMT has been offering DDR4 chips at about half the prevailing market rate

https://www.koreaherald.com/article/10679206
165•phront•12h ago•145 comments

EDuke32 – Duke Nukem 3D (Open-Source)

https://www.eduke32.com/
157•reconnecting•7h ago•59 comments

Claws are now a new layer on top of LLM agents

https://twitter.com/karpathy/status/2024987174077432126
206•Cyphase•1d ago•658 comments

Toyota Mirai hydrogen car depreciation: 65% value loss in a year

https://carbuzz.com/toyota-mirai-massive-depreciation-one-year/
104•iancmceachern•9h ago•244 comments

Canvas_ity: A tiny, single-header <canvas>-like 2D rasterizer for C++

https://github.com/a-e-k/canvas_ity
64•PaulHoule•8h ago•24 comments

Finding forall-exists Hyperbugs using Symbolic Execution

https://dl.acm.org/doi/full/10.1145/3689761
20•todsacerdoti•5d ago•0 comments

Inputlag.science – Repository of knowledge about input lag in gaming

https://inputlag.science
69•akyuu•7h ago•12 comments

Forward propagation of errors through time

https://nicolaszucchet.github.io/Forward-propagation-errors-through-time/
9•iNic•2d ago•0 comments

What not to write on your security clearance form (1988)

https://milk.com/wall-o-shame/security_clearance.html
394•wizardforhire•10h ago•176 comments

Acme Weather

https://acmeweather.com/blog/introducing-acme-weather
207•cryptoz•20h ago•126 comments

I verified my LinkedIn identity. Here's what I handed over

https://thelocalstack.eu/posts/linkedin-identity-verification-privacy/
1187•ColinWright•20h ago•416 comments

Personal Statement of a CIA Analyst

https://antipolygraph.org/statements/statement-038.shtml
182•grubbs•9h ago•106 comments

Be wary of Bluesky

https://kevinak.se/blog/be-wary-of-bluesky
257•kevinak•1d ago•176 comments

Permacomputing

https://wiki.xxiivv.com/site/permacomputing.html
109•tosh•4d ago•27 comments

I Don't Like Magic

https://adactio.com/journal/22399
118•edent•3d ago•97 comments

Uncovering insiders and alpha on Polymarket with AI

https://twitter.com/peterjliu/status/2024901585806225723
133•somerandomness•1d ago•126 comments

Keep Android Open

https://f-droid.org/2026/02/20/twif.html
2002•LorenDB•1d ago•693 comments

A16z partner says that the theory that we’ll vibe code everything is wrong

https://www.aol.com/articles/a16z-partner-says-theory-well-050150534.html
88•paulpauper•1d ago•128 comments

Online Pebble Development

https://cloudpebble.repebble.com/
22•teekert•6h ago•6 comments