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