Monday 24 October 2016

How to make ArrayList synchronized ?


ArrayList methods are non-synchronized but still if there is a need that we can make them synchronized as :
//Use Collecions.synzhonizedList method
List l = Collections.synchronizedList(new ArrayList());
...

//If you want to use iterator on the synchronized list, use it
//like this. It should be in synchronized block.
synchronized (l) {
  Iterator it = l.iterator();
  while (it.hasNext())
      ...
      it.next();
      ...

}

Difference Between ArrayList and Vector in JAVA


 ArrayList and Vector both are the implementation class of List interface and use resizable array as a data structure internally and insertion order is preserved. However there are few differences between ArrayList and Vector.

ArrayList Vs Vector

1) Synchronization: ArrayList is non-synchronized that means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environment
while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of storage, however the way they resized is different. ArrayList grow by half of its size when resized while Vector doubles the size of itself by default when grows.
3) Performance: ArrayList gives better performance because it is non-synchronized. Vector operations gives poor performance as they are thread-safe.

4) Legacy : ArrayList is not a legacy class, because it is introduced in JDK 1.2 version, where as Vector is a legacy class introduced in JDK 1.0 version