title: Why CopyOnWriteArrayList uses Volatile keyword along with Lock
body: <p>As I can see in the set method of COWArrayList, It acquires lock before performing mutative operaitons like &quot;set&quot;.<br />
  For e.g:</p>
  <pre><code>public E set(int index, E element) {
  
      final ReentrantLock lock = this.lock;
  
      lock.lock();
  
      try {
  
          Object[] elements = getArray();
  
          E oldValue = get(elements, index);
  
  
          if (oldValue != element) {
  
              int len = elements.length;
  
              Object[] newElements = Arrays.copyOf(elements, len);
  
              newElements[index] = element;
  
              setArray(newElements);
  
          } else {
  
              // Not quite a no-op; ensures volatile write semantics
  
              setArray(elements);
  
          }
  
          return oldValue;
  
      } finally {
  
          lock.unlock();
  
      }
  
  }
  </code></pre>
  <p>I do have two questions here, which i could not figure out:</p>
  <ol>
  <li>Acquiring lock will ensure other threads will see the updated state. Why volatile keyword is required with underlying array</li>
  <li>Why storing value of lock in final local variable &quot;final ReentrantLock lock = this.lock;&quot; instead of directly performing operation &quot;this.lock.lock&quot;.</li>
  </ol>