java - 迭代同步包装器是否安全?

标签 java multithreading synchronized

我决定深入研究一下源代码并注意到 Collections.synchronizedList(List)实现如下:

public static <T> List<T> synchronizedList(List<T> list) {
    return (list instanceof RandomAccess ?
        new SynchronizedRandomAccessList<T>(list) :
        new SynchronizedList<T>(list));
}

哪里SynchronizedList嵌套类是:

static class SynchronizedList<E>
extends SynchronizedCollection<E>
            implements List<E> {
    private static final long serialVersionUID = -7754090372962971524L;
    final List<E> list;

    SynchronizedList(List<E> list) {
        super(list);
        this.list = list;
    }
    SynchronizedList(List<E> list, Object mutex) {
        super(list, mutex);
        this.list = list;
    }

    public boolean More ...equals(Object o) {
        synchronized(mutex) {return list.equals(o);}
    }

    //ommited

    public void add(int index, E element) {
        synchronized(mutex) {list.add(index, element);}
    }

    public E remove(int index) {
        synchronized(mutex) {return list.remove(index);}
    }

    //rest is ommited
}

可以看出,该类使用一个private 锁对象来提供线程安全。但是the documentation允许我们使用锁定工厂方法返回的对象来迭代它。

It is imperative that the user manually synchronize on the returned list when iterating over it:

因此,我们使用不同的锁来迭代和修改列表(addremove 等)。

为什么认为它是安全的?

最佳答案

Collections#synchronizedList 方法

public static <T> List<T> synchronizedList(List<T> list) {
    return (list instanceof RandomAccess ?
            new SynchronizedRandomAccessList<>(list) :
            new SynchronizedList<>(list));
}

使用您在问题中显示的单参数构造函数。该构造函数调用将 this 设置为 mutex 的 super 构造函数。所有方法都在 mutex, this同步

文档告诉您在迭代时也要同步实例。该引用与方法主体中的 this 相同。

所有这些操作(应该,如果你做对了)因此共享同一个锁。

关于java - 迭代同步包装器是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34586323/

相关文章:

java - 获取 YouTube 直接上传的上传进度?

c++ - 基于 Qt 的 CD 开膛手的线程构建 block (TBB)?

multithreading - "C# 3.0 in a Nutshell"中关于线程的文本说明

Java同步块(synchronized block)

java - org.springframework.beans.factory.BeanCreationException : Injection of autowired dependencies failed;

java - 当我要求它在 toast 中显示保存的数据时,我的应用程序崩溃了 - 我

java - 某处缺少返回语句?

java - 使用 Runtime.exec() 生成的进程的高效执行和输出流重定向

数组列表上的 java volatile /同步

java - synchronized 关键字和实例方法上的锁