执行读取和“设置”是否安全?不带锁定机制的不同线程对List进行操作 [英] Is it safe to perform read and "set" operation on List by different threads without locking mechanism

查看:125
本文介绍了执行读取和“设置”是否安全?不带锁定机制的不同线程对List进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迭代 List 是非常不安全的,这是由另一个线程执行的添加/删除操作。

It is pretty unsafe to iterate over a List, which is being performed add / remove operation by another thread.

这就是我们需要的原因 CopyOnWriteArrayList

That's why we need need CopyOnWriteArrayList

public static void main(String[] args) throws InterruptedException {
    List<String> list = new ArrayList<>();

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                // java.util.ConcurrentModificationException
                for (String s : list) {
                    System.out.println(s);
                }
            }
        }

    });
    thread.start();

    for (int i=0; i<1000; i++) {
        list.add("string" + i);    
    }

    Thread.sleep(Long.MAX_VALUE);
}

然而,如何设置操作。目前,以下代码不会抛出任何异常。

However, how about set operation. Currently, the following code doesn't throw any exception.

public static void main(String[] args) throws InterruptedException {
    List<String> list = new ArrayList<>();
    list.add("dummy");

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                for (String s : list) {
                    System.out.println(s);
                }
            }
        }

    });
    thread.start();

    for (int i=0; i<1000; i++) {
        list.set(0, "smart");
    }

    Thread.sleep(Long.MAX_VALUE);
}

即使没有任何意外的结果,我也在想,如果线程只对列表执行 set 操作,我们不使用任何锁定机制或复制n写机制是一个好习惯吗?

Even though there isn't any unexpected outcome, I was wondering, if the thread only performing set operation on the List, is it a good practice that we don't using any locking mechanism, or copy n write mechanism?

推荐答案

引用 ArrayList


请注意,此实现未同步。如果多个线程同时访问ArrayList实例,并且至少有一个线程在结构上修改了列表,则必须在外部进行同步。 (结构修改是添加或删除一个或多个元素的任何操作,或显式调整后备数组的大小;仅设置元素的值不是结构修改。)

所以不,它不需要同步。

So no, it does not need to be synchronized.

这篇关于执行读取和“设置”是否安全?不带锁定机制的不同线程对List进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆