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 22 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 }