androidsynchronizedcopyonwritearraylist

CopyOnWriteArraylist synchronized methods


Its method from CopyOnWriteArrayList.class

public synchronized boolean set(E e) {
        Object[] newElements = elements.clone();
        @SuppressWarnings("unchecked")
        E result = (E) newElements[index];
        newElements[index] = e;
        elements = newElements;
        return result;
    }

Ok, lets say i have

final List<MyType> list = new CopyOnWriteArrayList();

and i have method

public void update(Task task) {
    synchronized (tasksList) {
            int index = tasksList.indexOf(task);
            validateIndex(index);
            tasksList.set(index, task);
        }
}

I thought than copyOnWriteArrayList synchronized method "set" on (this)

In my method i locked monitor my list ( synchronized (tasksList) ) why method works correct. I thought line ( tasksList.set(index, task); ) will not works because tasksList already blocked line above


Solution

  • The same thread can call a synchronized method within it - another synchronized method on the same instance. Since this thread owns the monitor issues a second call does not create.