I am using a java.util.concurrent.ConcurrentLinkedQueue
object to pass data between threads.
Should I declare my references volatile
?
Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.
ConcurrentLinkedQueue is an unbounded thread-safe queue which arranges the element in FIFO. New elements are added at the tail of this queue and the elements are added from the head of this queue. ConcurrentLinkedQueue class and its iterator implements all the optional methods of the Queue and Iterator interfaces.
For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
In short, no.
The value that your queue variable contains is a reference to the queue. This value won't change unless you reassign the queue like myQueue = otherQueue;
If all you are doing afer you create the queue is putting things in and taking things out then it doesn't matter if a thread has a cached value because the value (the reference to the queue) never changes.
It's good practice to make all variables final unless you need it to not be final.
No, since you are always using the same queue. Volatile means, that the value of a variable in memory will always be the same for every processor. Note that variables that are stored in a register will not be synchronised, even if you declare the variable 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