我有以下类(class)
public class Example{
public static List<String> list = new ArrayList<String>();
public static void addElement(String val){
synchronized(list){
list.add(val);
}
}
public static synchronized void printElement(){
Iterator<String> it = list.iterator();
while(it.hasNext()){
//print element
}
}
}
printElement方法中的iterator()调用会抛出ConcurrentModificationException吗?基本问题是如果获取了类对象的锁(如在 printElement 方法中所做的那样),它是否也会锁定类成员/变量?请帮我解答。
最佳答案
Does a lock on class, locks class variables too? - java
你的锁在你的实例上,而不是你的类。不,它只锁定实例。
Will the iterator() call in the printElement method throw ConcurrentModificationException?
如果该方法中的代码在迭代期间修改了列表,它就会执行。但是,如果该类中的所有代码也同步,并且您没有将该列表的引用提供给类之外的任何内容,那么您就知道只有该方法中的代码在运行。
不过,同步列表本身可能会更好。这样,即使您已经给出了对该列表的引用,假设使用它的所有代码都在其上同步,您也不会受到并发 mod 的影响:
public static void printElement(){
// ^--- No `synchronized ` here unless you REALLY need it for other reasons
synchronized (list) {
Iterator<String> it = list.iterator();
while(it.hasNext()){
//print element
}
}
}
如果您要提供引用资料并希望真的确定,请使用 Collections.synchronizedList
返回的列表或者来自 java.util.concurrent
package 的东西.
关于java - 锁定类是否也锁定类变量? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998336/