frontpage.
newsnewestaskshowjobs

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

Zig's new bitCast semantics and LLVM back end improvements

https://ziglang.org/devlog/2026/#2026-06-25
109•kouosi•3h ago•28 comments

IBM debuts sub-1 nanometer chip technology

https://newsroom.ibm.com/2026-06-25-ibm-debuts-worlds-first-sub-1-nanometer-chip-technology
27•porridgeraisin•1h ago•11 comments

A Herculaneum scroll has been read for the first time

https://scrollprize.org/firstscroll
42•verditelabs•1h ago•9 comments

You can't unit test for taste

https://dev.karltryggvason.com/you-cant-unit-test-for-taste/
177•kalli•1d ago•68 comments

Show HN: I made Google Trends for Hacker News by indexing 18 years of comments

https://hackernewstrends.com
398•ytkimirti•3h ago•113 comments

Apple raises prices of MacBooks, iPads

https://www.reuters.com/world/asia-pacific/apple-raises-prices-macbooks-ipads-memory-costs-skyroc...
250•virgildotcodes•4h ago•458 comments

Besimple AI (YC P25) Is Hiring

https://www.ycombinator.com/companies/besimple-ai/jobs/yWfhhOR-strategic-projects-lead-audio-data
1•yzhong94•31m ago

Half-Life 2 in a Browser

https://hl2.slqnt.dev/
544•panza•11h ago•222 comments

Tw-fade: pure CSS scroll-driven edge masking

https://pete.design/tw-fade
30•petekp•3d ago•12 comments

Windows 10 quietly gets one more year of support and updates

https://www.neowin.net/news/windows-10-quietly-gets-one-more-year-of-support-and-updates/
55•bundie•1h ago•29 comments

Anthropic says Alibaba illicitly extracted Claude AI model capabilities

https://www.reuters.com/world/china/anthropic-says-alibaba-illicitly-extracted-claude-ai-model-ca...
700•htrp•21h ago•1132 comments

OS9Map

https://yllan.org/software/OS9Map/
25•LaSombra•2h ago•1 comments

Show HN: Turn native language audio into flashcards and shadowing practice

https://lingochunk.com/try
47•alder•6h ago•24 comments

Physicists Track and Trap the Elusive Neutrino

https://www.quantamagazine.org/how-physicists-track-and-trap-the-elusive-neutrino-20260624/
14•ibobev•2h ago•1 comments

Deno 2.9

https://deno.com/blog/v2.9
77•enz•1h ago•26 comments

LastPass notifies users of yet another data breach

https://9to5mac.com/2026/06/23/lastpass-notifies-users-of-yet-another-data-breach/
350•mooreds•7h ago•155 comments

Ford AI hiccups push carmaker to rehire ‘gray beard’ inspectors

https://www.bloomberg.com/news/articles/2026-06-25/ford-has-been-rehiring-quality-inspectors-afte...
513•alanwreath•2h ago•254 comments

Political bias in AI: Where the AI models stand

https://trakkr.ai/bias
25•mektrik•4h ago•75 comments

SoftBank 2026 AGM [pdf]

https://group.softbank/media/Project/sbg/sbg/pdf/ir/investors/shareholders/2026/shareholders-meet...
39•dmmalam•4h ago•10 comments

Show HN: MiniPCs.zip – Charting the Pareto frontier of Mini PCs

https://minipcs.zip
55•yathern•4d ago•24 comments

Cloudflare launched self-managed OAuth for all

https://blog.cloudflare.com/oauth-for-all/
306•terryds•15h ago•134 comments

Wikipedia Workers in Britain set global first by seeking union recognition

https://utaw.tech/news/wikipedia-recognition
196•chobeat•10h ago•187 comments

Blogging can just be stating the obvious

https://blog.jim-nielsen.com/2026/blogging-stating-the-obvious/
390•Curiositry•17h ago•118 comments

Puzzling Success of Overparameterization: Lottery Tickets or Escape Dimensions?

https://infoscience.epfl.ch/entities/publication/9a49779b-f9f8-448d-b3d1-737c78455309
39•rbanffy•1d ago•8 comments

Medical students are using popular research tool to pump out misleading studies

https://www.science.org/content/article/medical-students-are-using-popular-research-tool-pump-out...
139•rndsignals•15h ago•76 comments

European Commission lines up Amazon and Microsoft for cloud gatekeeper status

https://www.theregister.com/legal/2026/06/25/european-commission-lines-up-amazon-and-microsoft-fo...
11•Bender•1h ago•0 comments

Bohemia Interactive: Cold War Assault Remastered Source Code on GitHub

https://github.com/BohemiaInteractive/CWR
171•dewey•2d ago•42 comments

Lianda and the Long March

https://blog.georeactor.com/books-06-26b
8•mapmeld•1d ago•0 comments

LuaJIT 3.0 proposed syntax extensions

https://github.com/LuaJIT/LuaJIT/issues/1475
210•phreddypharkus•16h ago•134 comments

Show HN: Secs-man, a secrets manager you can (not) rely on

https://github.com/Fran314/secrets-manager-rs
22•Fran314•5h ago•14 comments