I want to remove an object from a list, but I have a thread that is consistently checking the same list using an iterator. I already have the object that I want to remove, do I have to use another iterator to loop through the list, while checking for the object, then deleting it using the iterator or is there a simpler way of doing so? Right now, if I try and remove the object from the list using the remove method, the iterator on the thread gives me a NoSuchElementException
.
//Threaded loop.
Iterator<Client> playersIterator = getPlayers().iterator();
while(playersIterator.hasNext()){
Client c = playersIterator.next(); //NoSuchElementException
if(c.getSocket().isClosed()) {
playersIterator.remove();
if(getHost() == c) {
assignNewHost();
}
getServer().getLobbyHandler().updateGames();
}
}
//Use an iterator to remove?
public void removePlayerFromGame(Client client) {
Game g = getServer().getGame(client);
if(g != null) {
g.getPlayers().remove(client);
}
}
Use synchronized
to control the access to the resources...
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
synchronized {
// your code will wait before removing the object
g.getPlayers().remove(client);
}