Files
java-core-examples/cow/output/02-synchronizedlist-cme-demo.txt
T

12 lines
588 B
Plaintext

[reader] it.next() = Apple
[writer] syncList.add("Date") completed - list is now [Apple, Banana, Cherry, Date]
[reader] it.next() threw ConcurrentModificationException, as expected
Exception actually thrown: java.util.ConcurrentModificationException
=== The fix: synchronize the WHOLE iteration yourself, as the Javadoc instructs ===
holding the lock for the whole iteration - starting safeWriter now
iterated 3 elements with no exception, because safeWriter
cannot acquire the same monitor until this synchronized block exits
after the block: syncList2 = [Apple, Banana, Cherry, Date]