Thread-safety of BlockingQueue's drainTo() method

I think you are confusing the terms "thread-safe" and "atomic". They do not mean the same thing. A method can be thread-safe without being atomic, and can be atomic (for a single thread) without being thread-safe.

Thread-safe is a rubbery term that is hard to define without being circular. According to Goetz, a good working model is that a method is thread-safe if it is "as correct" when used in a multi-threaded context as it is run in a single-threaded context. The rubberyness is in the fact that correctness is subjective unless you have a formal specification to measure against.

By contrast, atomic is easy to define. It simply means that the operation either happens completely or it doesn't happen at all.

So the answer to your question is that drainTo() is thread-safe, but not atomic. It is not atomic because it could throw an exception half way through draining. However, modulo that, the queue will still be in a consistent state, whether or not other threads were doing things to the queue at the same time.


(It is implicit in the above discussion that the specific implementation of the BlockingQueue interface implements the interface correctly. If it doesn't, all bets are off.)


drainTo() is thread safe in the sense that any operation on the queue that happens at the same time will not change the result nor will it corrupt the state of the queue. Otherwise, the method would be pretty pointless.

You could run into problems if the target collection (the one to which the results are added) does something "clever". But since you usually drain the queue to a collection to which only a single thread has access, it's more of a theoretical problem.