Holliday Java Quiz: ConcurrentModificationException
Tomorrow is Thanksgiving in the US. And here is a little Java quiz that you may want to ponder on while the turkey is in the oven. (BTW, I just recently realized I've been pronouncing the word 'oven' wrong all these years. Apparently it's not [oh-vn], but [uh-vn].)
Q: For the following Foo.java, is it ever possible for line 21 to throw a java.util.ConcurrentModificationException?
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class Foo { 5 private final List<Bar> bars = new ArrayList<Bar>(); 6 7 public void add(Bar bar) { 8 synchronized(bars) { 9 bars.add(bar); 10 } 11 } 12 13 public void remove(Bar bar) { 14 synchronized(bars) { 15 bars.remove(bar); 16 } 17 } 18 19 public void close() { 20 synchronized(bars) { 21 for (Bar bar: bars) { 22 bar.close(); 23 } 24 bars.clear(); 25 } 26 } 27 }
Have a happy Thanksgiving.
Re: Holliday Java Quiz: ConcurrentModificationException
Even if bar.close() would call Foo.add(bar) or Foo.remove(bar), wouldn't that end in a deadlock? Note that the bar.close() call happens in a synchronized block with the lock taken on the bars field and also adding and removing methods inside Foo try to obtain that lock prior to executing something...
I don't see how a CME could be thrown...
Re: Holliday Java Quiz: ConcurrentModificationException
Since Bar is a reference other threads could be referencing the same instance of Bar (in this case Bars). Depending on what Bar.close() does you could have an exception thrown, but Bar does not necessarily need to be referencing Foo as stated above. Bar is an unknown in this case.