在Java中从多个线程读取(而不是修改)不是线程安全的对象(如链接列表)是否安全? [英] Is it safe in Java to read (not modify) objects which are not thread safe (like linked list) from multiple threads?
问题描述
已经有一个询问线程是否可以同时安全地读取/迭代LinkeList .似乎答案是肯定的,因为没有人从链接列表中进行过结构上的更改(添加/删除).
there was already a question whether threads can simultaneously safely read/iterate LinkeList. It seems the answer is yes as far as no-one structurally changes it (add/delete) from the linked list.
尽管有一个答案是关于未刷新的缓存"的警告,并建议您了解"java内存模型".所以我要详细说明那些邪恶的"缓存.我是新手,到目前为止,我仍然天真地相信以下代码是可以的(至少从我的测试中来说)
Although one answer was warning about "unflushed cache" and advicing to know "java memory model". So I'm asking to elaborate those "evil" caches. I'm a newbie and so far I still naively believe that following code is ok (at least from my tests)
public static class workerThread implements Runnable {
LinkedList<Integer> ll_only_for_read;
PrintWriter writer;
public workerThread(LinkedList<Integer> ll,int id2) throws Exception {
ll_only_for_read = ll;
writer = new PrintWriter("file."+id2, "UTF-8");
}
@Override
public void run() {
for(Integer i : ll_only_for_read) writer.println(" ll:"+i);
writer.close();
}
}
public static void main(String args[]) throws Exception{
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i=0;i<1e3;i++) ll.add(i);
// do I need to call something special here? (in order to say:
// "hey LinkeList flush all your data from local cache
// you will be now a good boy and share those data among
// whole lot of interesting threads. Don't worry though they will only read
// you, no thread would dare to change you"
new Thread(new workerThread(ll,1)).start();
new Thread(new workerThread(ll,2)).start();
}
推荐答案
是的,在您的特定示例代码中,这没关系,因为创建新线程的行为应定义在填充列表和从列表中读取之间的先发生后关系.另一种思路."但是,看似相似的设置有很多方法都是不安全的.
Yes, in your specific example code it's okay, since the act of creating the new thread should define a happens-before relationship between populating the list and reading it from another thread." There are plenty of ways that a seemingly-similar set up could be unsafe, however.
我强烈建议阅读Brian Goetz等人的"Java Concurrency in Practice"以获取更多详细信息.
I highly recommend reading "Java Concurrency in Practice" by Brian Goetz et al for more details.
这篇关于在Java中从多个线程读取(而不是修改)不是线程安全的对象(如链接列表)是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!