Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java concurrent collections are really thread-safe

I was looking at the code of java concurrent collections and I see that they just wrap simple collections with locking some lock in the beginning of the operation and unlocking it in the end.

What about volatile? If the back end collection is not volatile the changes could be missed by other threads, and so the thread-saving is somewhat broken. I know that synchronized can solve this issue, but they use just locks without any further synchronization.

Is that a problem, or am I missing something?


Update:

After a slight discussion I want to rephrase the question a bit.

I want to use a java collections in a multi threaded environment. (For instance currently I'm talking about PriorityBlockingQueue)

I want to be sure that the changes one thread makes to the collection (push/pop) are immediately visible to others.

It is good that java concurrent collections prevent me from diving into troubles to keep the inner state of the collection stable when number of threads updates it, but I want to be sure that the data itself is visible to all threads.

The question is: am I correct that java concurrent collections don't provide this feature out of the box? And if I do, what additional (minimalistic cost) techniques should I use in order to do provide the desired visibility?

Thanks.

like image 803
jutky Avatar asked Nov 23 '10 18:11

jutky


2 Answers

From BlockingQueue's Javadoc:

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

PriorityBlockingQueue provides this behaviour by means of a ReentrantLock which (being an implementation of Lock):

...provide[s] the same memory synchronization semantics as provided by the built-in monitor lock, as described in the JLS...

like image 68
SimonJ Avatar answered Sep 23 '22 07:09

SimonJ


yes, you are missing something. the ReentrantLock class provides the same guarantees as synchronized. And, ReentrantLock and synchronized both provide the same memory guarantees as volatile.

like image 27
james Avatar answered Sep 24 '22 07:09

james