Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Data corruption  RSS feed

 
Roger Nelson
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Hashmap having key value as string,Boolean, and if the get and put on it is being accessed by multiple threads without synchronization.
I presume the get method will always return either true or false.

Is there a possibility that the get() may return null or exception will be thrown, because the put() thread is currently updating the value ?
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think we can predict any of that. If you see multi thread accessing the shared HashMap its better to synch it using Collections.synchronizedMap or use Hashtable ...

Regards,
Maulin
 
Roger Nelson
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
This issue deals with multiple reader threads with single writer thread. And was looking to avoid synchronization delays during read access by multiple threads.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's rarely, if ever, a good idea to use Hashtable in new code.

Using a java.util.HashMap and Collections.synchronizedMap() will ensure that multi-threaded access will not corrupt the map itself. However, you need to think about whether that is the only threading issue in your code. Is the map part of any larger data structure that must be kept in sync? If so, you need wider synchronisation.

Final point, synchronisation for uncontended locks is very fast now. If there is a risk of simultaneous access to a changing data structure, it's best just to do the synchronisation, rather than work out some complicated way of avoiding it. Such avoidance is often broken anyway (e.g. DCL).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!