Tuesday, 12 December 2017

Which collection classes are synchronized or thread-safe?

Collection framework provides lots of classes to work with. Among them some are synchronized while other are non synchronized.

Recently one of my colleague was asked the same question in Deloitte interview. So you could also be asked the same in your next interview.

Lets come to the point.

All the synchronized collection classes are stated below:

1. Vector

Vector implements grow able array of objects. The elements in vector can be accessed using integer index just as we do in array.

Vector is synchronized so it should be used if thread-safety is concern of the developer. 
Due to synchronized nature, it does not allow multiple threads to access and modify its resources concurrently. If one thread has access to the vector then other thread wanting to access and operate on it must wait for its turn until the vector is released by the thread in action.

On other hand, this synchronized nature affects Vector’s performanceSo ArrayList is preferred over Vector if performance is to be considering factor.

To read about Vector in details. please follow the link Vector in java 

2. Hashtable

Hashtable extends Dictionary class and implements Map interface. Hashtable stores elements in key-value pair.

Hashtable is synchronized in nature.
Due to synchronized nature, it does not allow multiple threads to access and modify itself concurrently. 

Note: Both vector and hashtable are legacy classes and are not recommended for use.

3. CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe variant of ArrayList which was included in java version 1.5 or java 5.
Here thread-safe indicates that this collection class is synchronized.

Advantage of synchronization:
If you don't want any resource to be shared simultaneously by multiple threads then mark the resource Synchronized. This makes sure that only one thread can access the resource at one instance and others has to wait for their turn in the queue.

Disadvantage of synchronization:
Because of being synchronized in nature these classes are slow in terms of performance. Reason is simple. Because of synchronization only single thread is able to access the class resource at a time. Other thread has to wait in queue till the first thread completes its task on the resource. Thus multitasking is not possible which in turn impacts speed.

You may also like to read:

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.