views:

66

answers:

3

Hello Experts,

Could you please clarify if we need to use explicit synchronization or locks for using ConcurrentLinkedQueue? I am specifically interested in knowing if sync calls are needed for following ConcurrentLinkedQueue methods.

  • add
  • clear
  • size

Possibly size is the only method which might require explicit sync since it's a not an atomic method but ConcurrentLinkedQueue java docs say that

"Beware that, unlike in most collections, the size method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires a traversal of the elements. "

which make me believe that though size call may be slow but it doesn't require any explicit sync call.

Thanks in advance ...

A: 

You should not and do not need to use explicit locking on any of those methods.

Kevin
+1  A: 

You don't need any explicit synchronization or locks. As the docs state, it is a thread-safe collection. This mean each of these methods is correctly atomic (though as you point out, size() may be slow).

Nick Fortescue
A: 

Yeah, you do not need to use explicit synchronization because this is a thread safe collection. Any concurrent access is allowed without worry

vodkhang