• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiple threads reading from a Collection  RSS feed

 
Nitin Dubey
Ranch Hand
Posts: 126
Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Following is the code I have written. Are there any chances of ConcurrentAccessException to arise if multiple threads are calling isExcluded method? There is no synchronization stuff in the code below, once this data is loaded it will not be changed.

- Is the object locked while reading as well?
- I can also pack these things in a ConcurrentHashMap, what should work best?



I am trying to find out best way two write this kind of code.

Any help is appreciated.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nitin:Once this data is loaded it will not be changed.

This is the key. If you are sure that the data will not change then you have made the Set immutable and immutable objects do not need synchronization.

Nitin: Is the object locked while reading as well?

It depends on the implementation of the collection, eg: a Vector synchronize the read operations. HashSet does not do any synchronization.

Nitin: I can also pack these things in a ConcurrentHashMap, what should work best?

Since, you are using HashSet, so i dont think you can use ConcurrentHashMap with the same effect. Anyways, it is not required as you do not need synchronization here.
 
Nitin Dubey
Ranch Hand
Posts: 126
Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That means I can use immutable HashSet objects in multi-threaded environment without any risk.

Well, I now understand; it is very logical. The exception that is thrown in such cases is ConcurrentModificationException that itself means it is thrown only when there is any modification.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nitin:That means I can use immutable HashSet objects in multi-threaded environment without any risk.

Yep. Infact you can use *any* immutable object without worrying about multi-threading issues.

Nitin: Well, I now understand; it is very logical. The exception that is thrown in such cases is ConcurrentModificationException that itself means it is thrown only when there is any modification.[/QB]

Bang on !!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!