0

As I can see in the set method of COWArrayList, It acquires lock before performing mutative operaitons like "set".
For e.g:

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();

    }

}

I do have two questions here, which i could not figure out:

  1. Acquiring lock will ensure other threads will see the updated state. Why volatile keyword is required with underlying array
  2. Why storing value of lock in final local variable "final ReentrantLock lock = this.lock;" instead of directly performing operation "this.lock.lock".
Tarun
  • 3,162
  • 3
  • 29
  • 45
  • 3
    To answer you’re first question, have a read of the “read only” methods (get, contains etc). Do they lock? What is the implication of that? – Boris the Spider Dec 22 '21 at 07:07
  • @BoristheSpider get(int index) method uses lock – Tarun Dec 22 '21 at 07:11
  • 3
    And to answer your second question, it's a slight [performance optimization](https://stackoverflow.com/q/6602922/2541560) to access a local variable instead of an instance variable. While `get()` may use lock (it doesn't), not all the read methods do (such as `contains()`). – Kayaman Dec 22 '21 at 07:13
  • @BoristheSpider Contains method does not use. Are you saying only after unlock, the other thread (not using lock) is guranteed to see the updated reference in the underlying array. With Volatile the change would reflect immediately ? – Tarun Dec 22 '21 at 07:14
  • 1
    Don’t quite see where you see get using the lock. But anyway, the lock is irrelevant for guaranteeing visibility if not all threads use it. – Boris the Spider Dec 22 '21 at 07:16
  • Yes you are right, even get dont use it. I mistakenly looked into get method of sublist inner class. – Tarun Dec 22 '21 at 07:19
  • Got it, Thanks. – Tarun Dec 22 '21 at 07:25
  • Another answer for your second question:[link](https://stackoverflow.com/questions/2785964/in-arrayblockingqueue-why-copy-final-member-field-into-local-final-variable) – zysaaa Dec 22 '21 at 07:34

0 Answers0