美好的一天,併發Java的LinkedList類
我有一個Java中的LinkedList的併發問題。我有一個稱爲「連接」的對象類型,它具有名爲「偵聽器」的「MessageHandlers」的成員變量LinkedList。然後我有兩個不同的線程,一個修改和一個遍歷同一個LinkedList。
我見過很多其他的StackOverflow問題,建議使用sychronized代碼塊,但這似乎並沒有幫助所有。我也嘗試創建LinkedList作爲併發鏈表,但我仍然收到
Exception in thread "Thread-1" java.util.ConcurrentModificationException
異常。有沒有人有任何其他建議嘗試?這裏是我的代碼snipbits ...
public synchronized Object ReadObject() throws java.io.IOException
{
Object obj = null;
try
{
obj = input.readObject();
synchronized(listeners)
{
Iterator<MessageHandler> i = listeners.iterator();
while(i.hasNext())
{
i.next().MessageReceived(obj, this);
}
}
}
catch (IOException e)
{
e.printStackTrace();
throw e;
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
上述代碼是在我的連接對象。它從一個函數調用,該函數有一個套接字的ObjectInputStream從套接字讀取數據。「input」是ObjectInputStream的一個實例。
public void addNewLoggedInUser(User user) throws Exception
{
for(User u:loggedInUsers)
{
if(u == user)
{
throw new Exception("That user is already logged in");
}
}
//Add the new users
loggedInUsers.add(user);
synchronized(user.getConnection().getListeners())
{
user.getConnection().getListeners().add(this);
}
this.SendGameStatusUpdateToAllLoggedinPlayers();
}
我然後調用該方法user.getConnection()。getListeners()。添加(本),因此我得到的例外。
public Connection()
{
//Initialize the variables to NULL
socket = null;
output = null;
input = null;
receiveThread = null;
runReceiveThread = false;
listeners = Collections.synchronizedList(new LinkedList<MessageHandler>());
//Handle the ID counter. Now we have a unique ID for every connection that comes in
connectionID = counterID;
counterID = counterID + 1;
}
這是連接類的構造函數。注意他Collections.synchronizedList
任何想法?非常感謝您的幫助!
是否在同步塊參數中存在user.getConnection()。getListeners()和listeners實例? – George
['ConcurrentModificationException'](http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html)在迭代時更改列表(添加/刪除的元素)時引發超過它。您可以使用單個線程導致此異常。除非有多個線程同時訪問列表,否則不應該需要任何類型的併發收集。 –
http://ideone.com/pUPCn爲例。 –