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.

Phoenix LiveView 1.2 Released

https://phoenixframework.org/blog/phoenix-liveview-1-2-released
107•ksec•4h ago•25 comments

Honda Civics and the Evil Valet

https://juniperspring.org/posts/honda-evil-valet/
265•librick•8h ago•43 comments

Free SQL→ER diagram tool, runs in the browser, nothing uploaded

https://sqltoerdiagram.com/
116•robhati•5h ago•23 comments

GLM 5.2 Is Out

https://twitter.com/jietang/status/2065784751345287314
577•aloknnikhil•17h ago•314 comments

Noise infusion banned from statistical products published by Census Bureau

https://desfontain.es/blog/banning-noise.html
821•nl•19h ago•509 comments

Don't trust large context windows

https://garrit.xyz/posts/2026-05-06-dont-trust-large-context-windows
84•computersuck•3h ago•64 comments

Every Frame Perfect

https://tonsky.me/blog/every-frame-perfect/
709•ravenical•22h ago•228 comments

500-year-old monasteries outperform at digital transformation (U. of Zurich)

https://phys.org/news/2026-05-historic-monasteries-digital-countries.html
13•indynz•2d ago•3 comments

Tribblix: The retro Illumos distribution

http://tribblix.org/
36•naturalmovement•4h ago•13 comments

Treating pancreatic tumours may have revealed cancer's master switch

https://economist.com/science-and-technology/2026/06/12/treating-pancreatic-tumours-may-have-reve...
360•andsoitis•20h ago•130 comments

Building a serial and VGA "everything console"

http://oldvcr.blogspot.com/2026/06/building-serial-and-vga-everything.html
31•classichasclass•7h ago•2 comments

Python 3.14 garbage collection rigamarole

https://theconsensus.dev/p/2026/06/06/python-3-14-garbage-collection-rigamarole.html
54•eatonphil•1d ago•37 comments

Beagle: Git, URIs and all the dirty words

https://replicated.wiki/blog/uris.html
14•gritzko•2d ago•2 comments

FreeOberon – Open-Source, Cross-Platform, Free Pascal/Turbo Pascal-Like Language

https://github.com/kekcleader/FreeOberon
89•peter_d_sherman•2d ago•32 comments

Pyodide 314.0: Python packages can now publish WebAssembly wheels to PyPI

https://blog.pyodide.org/posts/314-release/
126•agriyakhetarpal•4d ago•31 comments

Making Claude a Chemist

https://www.anthropic.com/research/making-claude-a-chemist
42•gmays•6h ago•32 comments

Pac-Man, but you're the ghost

https://garrit.xyz/posts/2026-06-13-pac-man-but-you-re-the-ghost
89•mindracer•5h ago•40 comments

LaserWriter seeds

https://inventingthefuture.ghost.io/laserwriter-seeds/
18•frizlab•3d ago•0 comments

Weave: Merging based on language structure and not lines

https://ataraxy-labs.github.io/weave/
42•rohanat•6h ago•22 comments

Codex for open source

https://openai.com/form/codex-for-oss/
229•EvgeniyZh•2d ago•90 comments

Amazon CEO's talks with U.S. officials triggered crackdown on Anthropic models

https://www.wsj.com/tech/ai/amazon-ceos-talks-with-u-s-officials-triggered-crackdown-on-anthropic...
686•ls612•16h ago•501 comments

GameBoy Workboy

https://tcrf.net/Workboy
188•tosh•16h ago•65 comments

A low-carbon computing platform from your retired phones

https://research.google/blog/a-low-carbon-computing-platform-from-your-retired-phones/
289•vikas-sharma•1d ago•152 comments

Running DOS on Behringers DDX3216 with a DIY x86-Bios from Scratch

https://chrisdevblog.com/2026/06/08/running-dos-on-behringers-ddx3216-using-a-diy-x86-bios/
95•rasz•15h ago•22 comments

ReactOS (FOSS "Windows") achieves 3D-accelerated Half-Life on real hardware

https://www.phoronix.com/news/ReactOS-Running-Half-Life
218•jeditobe•10h ago•30 comments

Software Architecture Guide (2019)

https://martinfowler.com/architecture/
66•laxmena•5h ago•24 comments

RTX 5080 and RTX 3090 Setup: 80 Tok/s on Qwen 3.6 27B Q8

https://imil.net/blog/posts/2026/rtx-5080-+-rtx-3090-setup-80+-tok-s-on-qwen-3.6-27b-q8/
248•iMil•23h ago•86 comments

Appreciating Exif

https://brentfitzgerald.com/posts/appreciating-exif/
160•burnto•4d ago•34 comments

The adder at the heart of Intel's 8087 floating-point chip

https://www.righto.com/2026/06/intel-8087-adder-reverse-engineered.html
112•pwg•16h ago•27 comments

Police officer investigated for using AI to 'create evidence' in multiple cases

https://news.sky.com/story/derbyshire-police-officer-investigated-for-using-ai-to-create-evidence...
319•austinallegro•13h ago•156 comments