Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is java.util.concurrent.Future threadsafe?

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.

like image 648
S42 Avatar asked Dec 05 '11 18:12

S42


2 Answers

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).

like image 146
JB Nizet Avatar answered Oct 19 '22 07:10

JB Nizet


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

like image 44
John Vint Avatar answered Oct 19 '22 07:10

John Vint