Question

I am using a java.util.concurrent.ConcurrentLinkedQueue object to pass data between threads.

Should I declare my references volatile?

Was it helpful?

Solution

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.

OTHER TIPS

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 can declare it final, then declare it final. If you cannot, declare it volatile.

Declaring it volatile has no effects on the inner structure of the Queue though. It only adds additional synchronization when assigning the a new ConcurrentLinkedQueue()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top