简体   繁体   中英

Adding functionality to existing thread-safe class

For below code,

public class ListHelper<E>{
   public List<E> list = 
               Collections.synchronizedList(new ArrayList<E>());
   .....
   public synchronized  boolean putIfAbsent(E x){
      boolean absent = !list.contains(x);
      if(absent){
          list.add(x);
      }      
   }
}

Java author says,

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.

On performing putIfAbsent operation, Is this(above) the cause for failure in thread safety?

It's the wrong lock (syncs on ListHelper instead of on list ), further, since list is published as public - it's accessible to anyone with a pointer to the ListHelper object.

Make it private and make sure no one can access it directly (other then through the synchronized methods you'll provide) and make sure you're syncing when performing read as well - and you should be golden.

Another way to do it is to provide an unmodifiable copy of the list to the reader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM