当我使用offer和poll进行访问时,LinkedList是否是线程安全的? [英] Is LinkedList thread-safe when I'm accessing it with offer and poll exclusively?
问题描述
我有一个链表 samples
:
protected LinkedList<RawDataset> samples = new LinkedList<RawDataset>();
我将元素附加到线程1中的列表中,如下所示:
I'm appending elements to the list in thread 1 like this:
this.samples.offer(data);
我正在第二个线程中检索元素,如下所示:
And I'm retrieving elements from it in a second thread like so:
public RawDataset retrieveSample() {
return this.samples.poll();
}
这会被视为线程安全吗?即使线程1和2都在修改列表,它们只在列表的头部或尾部专门执行,对吧?
Would this be considered as thread-safe? Even though thread 1 and 2 are both modifying the list they only do so on either the head or the tail of the list exclusively, right?
如果不是任何人都指向我在Java API中的一个类,它带有 poll
/ offer
并且肯定是线程安全的?
If it isn't can anyone point me to a class in the Java API that comes with poll
/offer
and is sure to be thread-safe?
提前谢谢。
BTW: Collections.synchronizedList(new LinkedList ())
不允许我访问 offer
/ poll
。
BTW: Collections.synchronizedList(new LinkedList())
won't give me access to offer
/poll
.
推荐答案
LinkedList不是线程安全的。你必须自己做锁定。
LinkedList is not thread safe. You'd have to do the locking yourself.
尝试 ConcurrentLinkedQueue 或 LinkedBlockingDeque 相反,如果它符合您的需求,它们是线程安全的,但行为与LinkedList略有不同。
Try ConcurrentLinkedQueue or LinkedBlockingDeque instead if it fits your needs, they are thread safe but slightly different behavior than LinkedList.
这篇关于当我使用offer和poll进行访问时,LinkedList是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!