Is it a general practice in Java world to synchronize ArrayList or HashMap (if we have to use them in multi-threaded application) ? Why should we synchronize ArrayList or HashMap instead we could use their corresponding Synchronized collections like CopyonArrayList or ConcurrentHashMap. Which by default are threadsafe?
There are 2 types of implementation available for thread safety, 1) CopyOnArrayList or Collections.synchrnozied* 2) ConcurrentAPIs.
Both provides thread safety but basic difference in their locking mechanism.
Type 1 uses synchronized keyword and makes all the method synchronized that means only 1 thread can access the API at one time. This results
performance issue when several threads are involved.
Type 2 uses bucket approach. In this default 16 buckets are used and each bucket is individual locked. So threads in different buckets can work
together which then improves performance. Only particular bucket is locked instead of complete lock on map.
As per javadocs basic difference between them are as below:
copyOnWriteArrayList: Thread Safe variant of array list
a) All operations are performed on fresh copy of underlying array.
b) Too costly but will be good if more reading than writing
c) Iterator iterates on copy of array when it is created. Never changes in life time of Iterator and hence no
concurrent modification exception
a) Returns a synchronized list backed by the specified list
b) Read operations are not synchronized. So need to synchronized when multiple threads accessing.
c) Better performance if write operation are more then read operations
You can't expect to wield supreme executive power just because
a bit of art, as a gift, that will fit in a stocking