gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:46 25 4
gpt4 key购买 nike

我决定深入研究一下源代码并注意到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com