• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threadsafe Collections question  RSS feed

 
narendra nath
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Goodfolks,

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?

Sorry this might be a very basic question.

Thanks
Nath
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Narendra,

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.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think a bit more explanation would be called for, please, since this is the Beginning forum.
 
narendra nath
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tushar,

I was wondering why should we create a synchronized arraylist (like shown below to make it thread safe) instead we could use CopyOnArrayList collection which is thread safe already.



Thanks
nath
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Collections.synchronizedList:

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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!