Java 我的局部变量是对外部集合的引用吗?锁定是否锁定原始集合?
我有两个类,其中一个包含一个应该始终同步的列表,但我想使用访问器Java 我的局部变量是对外部集合的引用吗?锁定是否锁定原始集合?,java,android,multithreading,locking,Java,Android,Multithreading,Locking,我有两个类,其中一个包含一个应该始终同步的列表,但我想使用访问器 class MyObject { private List<Thing> things = Collections.synchronizedList(new ArrayList<>()); public List<Thing> getThings() { return things; } } 类MyObject{ private List things=Collection
class MyObject {
private List<Thing> things = Collections.synchronizedList(new ArrayList<>());
public List<Thing> getThings() { return things; }
}
类MyObject{
private List things=Collections.synchronizedList(新的ArrayList());
public List getThings(){return things;}
}
在另一个类(Android活动)中,我希望安全地迭代集合
class MyActivity {
private void someMethod() {
List<Thing> localThings = myObjectInstance.getThings();
//we have to manually synchronise when iterating synchronizedList
synchronized(localThings) {
for (Thing thing : localThings) {
//do something to a thing
}
}
}
}
类MyActivity{
私有方法(){
List localThings=myObjectInstance.getThings();
//在迭代synchronizedList时,我们必须手动同步
同步(本地事物){
for(Thing:localThings){
//对某事做某事
}
}
}
}
我的问题是,在我上面的代码块中发生了什么?我的localThings
变量是指向与MyObject::things
相同集合的指针,还是我创建了一个新集合(在这种情况下,我不需要同步)。如果是前者,我是否通过这样做来保持线程安全(原始集合是否已锁定)
我的问题是,在我上面的代码块中发生了什么?是我的
localThings变量指向与
MyObject::事物
对。您返回内容
,其中内容
是一个引用。调用方收到引用的副本,该副本必然引用同一对象
或者我是否创建了一个新集合(在这种情况下
我不需要同步)
否,但您可以创建并返回新的列表
:
return new ArrayList<Thing>(things);
如果是前者,我是吗
通过这样做保持线程安全(是原始集合
锁着的
假定
localThings
引用的集合是由Collections.synchronizedList()
提供的同步列表包装器,并且您在该对象上的同步块内对其进行迭代,则在控件离开同步块之前,其他线程将无法调用该列表的任何方法。如果在迭代过程中,其他线程可能在列表中添加元素或从列表中删除元素,那么这种互斥级别是必要的,并且足以防止这种情况发生。很好,您回答了我需要的所有问题。谢谢(我只是担心只是偶然在副本上同步)
return Arrays.asList(things.toArray(new Thing[0]));