[concurrency-interest] Example from JCIP contains visibility problem?

Peter Veentjer alarmnummer at gmail.com
Mon Jan 7 03:44:59 EST 2008


Hi Guys,

I have a question about an example from JCIP. This example was used in
a presentation within our company, but I think the example contains a
visibility problem.

  @ThreadSafe
public class ListHelper<E> {

    public List<E> list = Collections.synchronizedList(new ArrayList<E>());

    // ...

    public boolean putIfAbsent(E x) {
        synchronized (list) {
            boolean absent = !list.contains(x);
            if (absent)
                list.add(x);
            return absent;
        }
    }
}

There is no happens before relation between the write of list and the
read of list, so there is no guarantee that the value read for the
synchronized block, contains the value written when this class is
initialized.

The fix is simple: make list final.

Is my assumption correct?


More information about the Concurrency-interest mailing list