1

I made a hashmap of objects in my service, as a private member variable. But, I heard that hashmaps are not good for parallel programming. I do not understand what this means, what implications/side-effects it can have on my service. I came across concurrent hashmaps. Should I use those instead. What are the difference between both and when should one or the other be used ? If anybody has knowledge in this area, please help !

superuser
  • 625
  • 3
  • 7
  • 19
  • unless your android app is multi-threaded and the thread use the hashMap, then you do not need to worry. – Scary Wombat Jan 15 '14 at 08:41
  • Take a look: http://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap – Ali Jan 15 '14 at 08:45
  • But what I do not understand is, the hashmap object I have created is not static. So, every thread will have it's own object of hashmap (unless different threads work on the same object), and will not interfere with the other threads' hashmap. In this case, I do not need to worry about making my hashmap concurrent/thread-safe. Right. – superuser Jan 15 '14 at 08:57

1 Answers1

1

When you talk about parallel programming in java you only talk about multi-threaded applications. You need to worry about your data-structures to be thread safe only if more than one thread could access to that data structure. This has nothing to do with the data-structure being static or an instance variable. If in your service you create more than on thread for example, and all those thread access the hash-map you probably need to sync the access to that hash-map. In those cases even if you use a thread-safe data-structure please keep in mind that the thread-safety is guaranteed only on the single operation. That means, for example that if you have a piece of code that does multiple operations on the data structure and you want those operations to be atomic you have to sync yourself the threads in order to make this transaction atomic. To better understand this argument please have a look at http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

Pasquale Anatriello
  • 2,355
  • 1
  • 16
  • 16