I am trying to find documentation indicating if java.util.concurrent.Future is/is not threadsafe. Eg can I safely give the same instance of Future to multiple threads, which will all call Future.get(...)?
I have tested code using Future in this manner and it seems to work fine but I'd be much happier if I could find documented expectation that future is safe for concurrent access in this manner.
Thanks.
Given that Future is intended to be used by several threads (at least the one which submits, and the one which sets its result), and given that the documentation specifies that there is a happen-before relationship between the asynchronous computation and the actions occurring after the get call, I would assume that the implementations are thread-safe (at least the standard implementations).
If you are using a Future
returned from an ExecutorService
, then yes they are guaranteed to be thread-safe. Since Future is an interface, the creator of the interface cannot guarantee that all implementations would be thread-safe though.
Nizet does bring up a good point though. The doc's say that implementations of the Future interface should be thread safe, not making the implementation thread-safe would then violate the Future's contract
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With