spotify / completable-futures

Utilities for working with futures in Java 8
Apache License 2.0
393 stars 51 forks source link

UnmodifiableFuture? #65

Open trustin opened 4 years ago

trustin commented 4 years ago

When returning a CompletableFuture to a caller, I sometimes need to make sure it is never completed by the caller. I could return a CompletionStage but it is still possible for a user to misuse it by converting it with toCompletableFuture().

So, I wrote a new class called UnmodifiableFuture:

Are you interested in making this a part of completable-futures? Then, I'd be happy to polish it a little bit and send a pull request.

spkrka commented 4 years ago

Couldn't you just return x.thenApply(Function.identity()) instead of x to prevent x from being completed by the caller?

trustin commented 4 years ago

It doesn't prevent a user from completing the returned future anyway. If it's passed to some other component, then we have the same problem, and I'd like to avoid using thenApply(Function.identity()) whenever I pass it around. It also creates an additional future object.

trustin commented 4 years ago

Also, we can create a singleton UnmodifiableFuture that's been completed with null and reuse it in many places, which is a GC-wise win.

spkrka commented 4 years ago

What about https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/concurrent/CompletableFuture.html#minimalCompletionStage() ? Can't that be used instead?

trustin commented 4 years ago

Not in Java 8, because it's added in 9. :sob: (It's also less verbose to call .join() or .get() because minimal stage must be converted to future.)

mattnworb commented 4 years ago

I like the idea 👍

trustin commented 4 years ago

Gentle ping :wink: