Я получаю java.util.ConcurrentModificationException.
Соответствующий код:
for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
// Do something
it.remove();
}
Когда вызывается it.remove(), он выдает мне это исключение.
Этот код находится внутри класса @Serviceannotated:
@Service
public class AuditService {
public AuditService(
this.pendingAudits = new ArrayList<Audit>();
}
public void flush(Audit... audits) {
this.pendingAudits.addAll(Arrays.asList(audits));
try {
for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
// Do something
it.remove();
}
}
}
}
Проблема возникает, когда до кода доходят два запроса.
Как я мог избежать этого исключения одновременного доступа?
Не могли бы вы дать ответ с небольшим вспомогательным кодом?
Итераторы @Lorelorelore, полученные из SynchronizedList, должны вручную синхронизироваться их пользователями.




Перво-наперво, это не проблема Spring. Это просто проблема с одновременной модификацией одного не очень удобного класса ArrayList.
Самым простым решением было бы синхронизировать доступ к методу, который его изменяет.
public synchronized void flush(Audit... audits) { }
Имейте в виду, что это приведет к последовательному выполнению метода flush, что приведет к огромному снижению производительности.
Замечание: недостаточно синхронизировать саму коллекцию с помощью Collections.synchronizedList - экземпляры итераторов, возвращаемые синхронизированными оболочками, требуют ручной синхронизации.
Разве это не очевидно? Вы обмениваетесь данными без надлежащей синхронизации.
Аннотированный класс @Service обычно представляет собой одноэлементный класс области видимости, и, следовательно, один и тот же экземпляр будет использоваться всеми вызывающими потоками.
Это приводит к тому, что все потоки обращаются к методу flush в одном и том же экземпляре.
И угадайте, что?
Ваш метод очистки пытается изменить список ArrayList, который является переменной-членом. Это делает его небезопасным в многопоточном сценарии.
Хорошее время вернуться к документации ArrayList, в которой рассказывается гораздо больше об итераторе.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(...)); The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
Я думаю, вы, вероятно, поместили Audit в список pendingAudits и хотите очистить их все, когда вы вызываете метод flush (Audit ...), вы можете использовать ConcurrentLinkedQueue вместо ArrayList.
public AuditService(
this.pendingAudits = new ConcurrentLinkedQueue<Audit>();
}
public void flush(Audit... audits) {
this.pendingAudits.addAll(Arrays.asList(audits));
try {
Audit audit;
while ((audit = this.pendingAudits.poll) != null) {
// Do something
}
}
}
The problem appears when two requests reach the code- может, пора задуматься о синхронизации?