Question

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 !

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top