6 Replies Latest reply on Nov 23, 2010 1:53 PM by 640409

    question realted to concurrent


      I just read the book "Java concurrency in pratice" and there is something I don;t quite understand.
      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)
              return absent;
      public class ImprovedList<T> implements List<T> {
          private final List<T> list;
          public ImprovedList(List<T> list) { this.list = list; }
          public synchronized boolean putIfAbsent(T x) {
              boolean contains = list.contains(x);
              if (contains)
              return !contains;
          public synchronized void clear() { list.clear(); }
          // ... similarly delegate other List methods
      Whatever lock the List uses to guard its state, it sure isn't the lock on the ListHelper. ListHelper provides only the illusion of synchronization; the various list operations, while all synchronized, use different locks, which means that putIfAbsent is not atomic relative to other operations on the List. So there is no guarantee that another thread won't modify the list while putIfAbsent is executing.

      ImprovedList adds an additional level of locking using its own intrinsic lock. It does not care whether the underlying List is thread-safe, because it provides its own consistent locking that provides thread safety even if the List is not thread-safe or changes its locking implementation.

      what I don't quite understand is the client will not use the underlying list directly for ListHelper which is the same as ImprovedList.