简体   繁体   English

LinkedList.addAll在多线程应用程序中触发空指针异常

[英]LinkedList.addAll fires null pointer exception in multithreaded application

I have a LinkedList that is being modified by a single thread. 我有一个由单个线程修改的LinkedList。 But there are many threads reading it. 但是有许多线程在阅读它。

protected volatile LinkedList<V> list = new LinkedList<V>();

I need to retrieve this list at some point. 我需要在某个时候检索这个列表。 So, when I do, 所以,当我这样做的时候,

List<V> retList = new LinkedList<V>();
retList.addAll(list);
return Collections.unmodifiableList(list);

I receive the following exception 我收到以下异常

java.lang.NullPointerException at java.util.LinkedList.toArray(LinkedList.java:866) at java.util.LinkedList.addAll(LinkedList.java:269) at java.util.LinkedList.addAll(LinkedList.java:247) java.util.LinkedList.adArray(LinkedList.java:266)java.util.LinkedList.adArray(LinkedList.java:266)java.util.LinkedList.addAll(LinkedList.java:247)java.lang.NullPointerException

I have checked that the list or the values within it are not null. 我已检查列表或其中的值不为空。 What is the correct approach when you have a single writer-multiple readers. 当你有一个作家 - 多个读者时,正确的方法是什么。 The aim is not to have a synchronized list. 目的不是要有一个同步列表。

Your volatile tag doesn't mean anything -- this has to do with the thread safety of the writable object. 易失性标记并不意味着什么 - 这与可写对象的线程安全性有关。 If you do not want to implement proper memory barriers yourself, then you need to use a different class, like maybe: 如果您不想自己实现适当的内存屏障,那么您需要使用不同的类,例如:

Instead of: 代替:

protected volatile LinkedList<V> list = new LinkedList<V>();

Try using: 尝试使用:

protected Deque<V> list = new [LinkedBlockingDeque][1]<V>();

I assume your using LinkedList instead of ArrayList because you want the Deque methods rather then the list methods. 我假设您使用LinkedList而不是ArrayList,因为您需要Deque方法而不是list方法。

If you really need list methods instead of dequeu methods, you can use CopyOnWriteArrayList 如果您确实需要list方法而不是dequeu方法,则可以使用CopyOnWriteArrayList

Anyway -- You need something that spits out a weakly consistent iterator rather then one of the standard java.util collections which all disclaim in their javadocs that they are not inherently thread-safe with any mix of readers and writers and are thus inappropriate for your use case without proper memory barriers. 无论如何 - 你需要一些东西吐出一个弱的一致迭代器而不是一个标准的java.util集合,这些集合都在他们的javadoc中声称它们对于任何读者和作者的混合本身并不是线程安全的,因此不适合你的用例没有适当的内存障碍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM