[concurrency-interest] Example from JCIP contains visibilityproblem?

David Holmes dcholmes at optusnet.com.au
Mon Jan 7 05:27:36 EST 2008


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