[concurrency-interest] Example from JCIP contains visibilityproblem?

Peter Veentjer alarmnummer at gmail.com
Mon Jan 7 05:53:13 EST 2008


Hi David,

thanks. I understand that the example could be safely used when the
variable pointing to the helper is safely published. The problem is
that this isn't very clear from the example (nothing is mentioned
about it) and that most developers don't understand the JMM. When
people see this example, they think this is the correct way to use
this class without knowing anything about the hidden/additional
requirements. Personally I prefer to localize this whenever I can and
in this case it could be solved by making the list variable final (or
volatile). Localizing also makes is easier to reason about concurrent
objects because you don't need to know how it is going to be used.

On Jan 7, 2008 11:27 AM, David Holmes <dcholmes at optusnet.com.au> wrote:
> Peter,
>
> The example doesn't show how the instance of ListHelper is created or
> shared. The ListHelper instance needs to be safely published.
>
> Cheers,
> David Holmes
>
>
> > -----Original Message-----
> > From: concurrency-interest-bounces at cs.oswego.edu
> > [mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of Peter
> > Veentjer
> > Sent: Monday, 7 January 2008 6:45 PM
> > To: concurrency-interest
> > Subject: [concurrency-interest] Example from JCIP contains
> > visibilityproblem?
> >
> >
> > 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?
> > _______________________________________________
> > Concurrency-interest mailing list
> > Concurrency-interest at altair.cs.oswego.edu
> > http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
> >
>
>


More information about the Concurrency-interest mailing list