Search This Blog

Monday, May 14, 2018

How Collections.synchronized works in Java

Synchronised collections are the "thread safe" Collections introduced by earlier Java versions(1.2 thru 1.4), which addresses synchronization by making all the public methods of the collection "Synchronized". 

Any compound operation needs to be supported with "client side Locking"

Example for a compound operation is any operation , that has "check and do", say "AddLast" element, which would first check/aquire the Size and then add the last element.
Even though both the operations, are protected by synchronised keyword, in between these operations, there is a possibility of a add/Remove operation, which can alter the size.

A remove operation in between Getsize() and Add()  can hence cause AddLast () to throw "OutofBound" Exception,
A add operation in between Getsize() and Add() can cause AddLast to add an entry before Last, and hence not performing the intended function

Java guards the collections like - 

        public boolean add(E e) {
            synchronized (mutex) {return c.add(e);}
        }

        public boolean remove(Object o) {
            synchronized (mutex) {return c.remove(o);}
        }


        public boolean containsAll(Collection<?> coll) {
            synchronized (mutex) {return c.containsAll(coll);}
        }

        public boolean addAll(Collection<? extends E> coll) {
            synchronized (mutex) {return c.addAll(coll);}
        }

        public boolean removeAll(Collection<?> coll) {
            synchronized (mutex) {return c.removeAll(coll);}
        }

        public boolean retainAll(Collection<?> coll) {
            synchronized (mutex) {return c.retainAll(coll);}
        }

        public void clear() {
            synchronized (mutex) {c.clear();}
        }

I love to discuss if you have any questions about the above post.

No comments :

Post a Comment