Understanding synchronous behavior

I am trying to improve my understanding of the blocking area issued during a call synchronized.

For instance:

class CopyOnReadList<T> {

    private final List<T> items = new ArrayList<T>();

    public void add(T item) {
        items.add(item);
    }

    public List<T> makeSnapshot() {
        List<T> copy = new ArrayList<T>();
        synchronized (items) {
            // Make a copy while holding the lock.
            for (T t : items) copy.add(t);
        }
        return copy;
    }

}

(The code is lovingly borrowed from this excellent answer )

In this piece of code, you can call one thread add, and the other - makeSnapshot?. Those. Does the lock created synchronized (items)affect all attempts to read on itemsor only those that were attempted using the method makeSnapshot()?

The original post actually used the lock synchonizedin the add method:

public void add(T item) {
    synchronized (items) {
        // Add item while holding the lock.
        items.add(item);
    }
}

What is the side effect of removing this?

+2
source share
3 answers

, makeSnapshot() , , , () ( , ).

add() , add() items , , , makeSnapshot().

add() , . WHILE .

+2

, - makeSnapshot?

- ConcurrentModificationException, .

() , makeSnapshot() ?

. items, , snychronize - , , .

+1

, makeSnapshot?

. synchronized , , , ( CopyOnReadList). , add , makeSnapshot.

add, -, ArrayList .

: ( ) .

+1

All Articles