I have following code for a chat server application in Java –
public synchronized List<ChatMessage> getMessages(int messageNumber) {
return messages.subList(messageNumber + 1, messages.size());
}
public synchronized int addMessage(ChatMessage c) {
messages.add(c);
return messages.size()-1;
}
I have following test code –
public static void main(String[] args) {
final ChatRoom c = new ChatRoom();
Thread user1 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<1000;i++) {
c.addMessage(new ChatMessage());
c.getMessages(0);
}
}
});
Thread user2 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<1000;i++) {
c.addMessage(new ChatMessage());
c.getMessages(0).size();
}
}
});
user1.start();
user2.start();
}
I am getting a ConcurrentModificationException.
How is this possible?
Your
getMessagesmethod just returns a view on the original list. It doesn’t create a copy of the list. So one thread is using a view on the list while another modifies the list – at that point, you get the exception.From the docs for
List.subList:It’s not clear what you’re really trying to achieve here, but fundamentally you can’t use
subListto magically create a thread-safe list 🙂