Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare java.util.concurrent.ConcurrentLinkedQueue references volatile?

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

Should I declare my references volatile?

like image 674
Jared Lindsey Avatar asked Dec 31 '13 14:12

Jared Lindsey


People also ask

Is volatile thread-safe in java?

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.

What is ConcurrentLinkedQueue?

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.

What is volatile keyword in java?

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.


2 Answers

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.

like image 197
Mike B Avatar answered Sep 19 '22 00:09

Mike B


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.

like image 28
Sibbo Avatar answered Sep 21 '22 00:09

Sibbo