美好的一天,我创造了Singleton:
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
public enum Singleton {
FIRST_INSTANCE;
String[] scrabbleLetters = {
"a","a","a","a","a","a","a","a","a","b","b","b","b","b","b","b","b","b",
"c","c","c","c","c","c","c","c","c","d","d","d","d","d","d","d","d","d","d",
};
private LinkedList<String> letterList = new LinkedList<>(Arrays.asList(scrabbleLetters));
private Object lock = new Object();
private Singleton() {
Collections.shuffle(letterList);
}
public static Singleton getInstance() {
return FIRST_INSTANCE;
}
public LinkedList<String> getLetterList() {
synchronized (lock) {
return FIRST_INSTANCE.letterList;
}
}
public LinkedList<String> getTiles(int howManyTiles) {
synchronized (lock) {
LinkedList<String> tilesToSend = new LinkedList<>();
for(int i=0; i<= howManyTiles; i++) {
tilesToSend.add(FIRST_INSTANCE.letterList.remove(0));
}
return tilesToSend;
}
}
}
我用这个例子测试了线程的安全性:
import java.util.LinkedList;
public class ScrabbleTest {
public static void main(String[] args) {
Runnable getTiles = () -> {
System.out.println("In thread : " +Thread.currentThread().getName());
Singleton newInstance = Singleton.getInstance();
System.out.println("Instance ID: " + System.identityHashCode(newInstance));
System.out.println(newInstance.getLetterList());
LinkedList<String> playerOneTiles = newInstance.getTiles(7);
System.out.println("Player : " + Thread.currentThread().getName() + playerOneTiles);
System.out.println("Got Tiles for " + Thread.currentThread().getName());
};
new Thread(getTiles, "First").start();
new Thread(getTiles, "Second").start();
}
}
执行10次之后,我确信没有问题,但是当我上次运行它时,我收到了这个堆栈跟踪:
In thread : Second
In thread : First
Instance ID: 1380197535
Instance ID: 1380197535
[d, d, b, c, b, b, a, d, c, d, a, d, c, a, a, d, c, a, a, b, d, b, b, a, b, c, a, d, c, a, c, b, c, c, b, d, d]
Player : First[d, d, b, c, b, b, a, d]
Got Tiles for First
Exception in thread "Second" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at java.util.AbstractCollection.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at ScrabbleTest.lambda$0(ScrabbleTest.java:10)
at java.lang.Thread.run(Unknown Source)
此异常很少退出,大约1次执行20次。 我发现,当不允许这样的修改时,检测到对象的并发修改的方法可能抛出ConcurrentModificationException。在代码中我有一个锁可以防止这种情况,有相同的锁用于更改和检索同步块的列表。我甚至没想到为什么会这样。
答案 0 :(得分:1)
CME
与并发性没有多大关系,因为名称可能会让你思考。 CME
最常见的情况是单线程上下文。但是,在这种情况下,也涉及线程。
您的问题来自tilesToSend.add(FIRST_INSTANCE.letterList.remove(0));
,其中您正在修改letterList
,但println
会同时对其进行迭代。同步在这里不会有所帮助,因为您必须同步比实际可能更大的块。
这里的简单解决方案是在getLetterList()
中返回列表的副本,如
return new LinkedList<>(FIRST_INSTANCE.letterList);
这样,remove()
可以修改原始列表,而println
正在迭代副本。