A LinkedList
has convenient peek
, pop
, ... methods.
Unfortunately, I need a thread-safe LinkedList
. So, my first idea was to wrap it as follows:
List<Object> list = Collections.synchronizedList(new LinkedList<>());
However, since the List
interface does not contain the peek
or pop
methods. This doesn't work of course.
Alternatively, I could use synchronized(list)
blocks all over the code. Is that the way to go ?
Any solutions that I'm overlooking ?
EDIT:
There are many reasons why one would use a LinkedList
. I see some people are proposing other collections. So, here follow the brief requirements, which lead to my decision of using a LinkedList
.
More background information:
- I'm using a LinkedList because the items need to be ordered.
- Items should be added in a non-blocking way.
- Items are added in the back ; removed from the front.
- Before the first item is removed, it first needs to be
peek
ed and validated. If validation fails, then the item needs to stay in the list. - Only if the validation completed successfully, then the first item is removed.
- The queue needs to have a maximum size (to avoid memory issues).
BlockingQueue
would be a better choice. It's designed for concurrent access, and supportspeek
andtake
(which is basicallypop
). – IsoelectronicConcurrentLinkedDeque
. – BloodfinLinkedBlockingDeque
– Steak