Home > Java > javaTutorial > Why Do I Get ConcurrentModificationException Even When Using `synchronized`?

Why Do I Get ConcurrentModificationException Even When Using `synchronized`?

Patricia Arquette
Release: 2024-11-09 01:56:02
Original
287 people have browsed it

Why Do I Get ConcurrentModificationException Even When Using `synchronized`?

How Can I Get ConcurrentModificationException Despite Using Synchronized?

It's common to assume that using the synchronized keyword prevents all concurrency issues. However, it only ensures that one thread at a time can access a synchronized block of code. It doesn't prevent modifications to the collection being iterated upon.

Consider the following code:

public synchronized X getAnotherX() {
  if (iterator.hasNext()) {
    X b = iterator.next();
    String name = b.getInputFileName();
    ...
    return b;
  } else {
    return null;
  }
}
Copy after login

The synchronized declaration header only ensures that the entire method is executed by one thread at a time. However, it doesn't prevent the collection that the iterator is accessing from being modified by other threads.

Why Does ConcurrentModificationException Occur?

ConcurrentModificationException typically occurs when you modify the collection being iterated upon within the iteration loop. For instance, the following code will cause this exception:

Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
    Item item = (Item) iterator.next();
    if (item.satisfiesCondition()) {
        collection.remove(item);
    }
}
Copy after login

In this case, you should use the iterator.remove() method to remove elements instead. If you need to add to the collection, you can't rely on synchronized methods. However, if you're dealing with a list, you can use the ListIterator subtype, which provides an add() method.

The above is the detailed content of Why Do I Get ConcurrentModificationException Even When Using `synchronized`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template