|
|
|
Back to newsletter 202 contents
Is HashMap thread-safe? Most of you reading this will immediately know the answer, but if you don't or are at all uncertain, pause and decide before reading on to the answer. The rest of you are shouting "of course it isn't"! So should you use it in a multi-threaded application where it will be used concurrently? If you immediately shouted "no!", then you're not wrong ... but you're not necessarily right either.
For example, if you have done all the updating of the HashMap in a single thread or synchronized, then after that it's safe to access it from multiple threads (if they have the view of the map after updating has finished). I'm not proposing you do this, because it makes it fragile for maintenance - if you did this, and later some other programmer decided they need to change something in the HashMap when it's in the concurrent access section of the code, then they might just proceed without synchronizing across all threads because they might not be thinking about concurrent access. My point here is that concurrent use of objects and data structures is not just about about the subtleties of thread-safety while you're implementing the functionality, you also need to worry about how robust your thread-safety is for later maintenance.
For this reason, you want to encapsulate your data structures so that it's much easier to think about them in isolation rather than how they're used through the application. If all of your accesses and updates to your data structure are controlled by your class, you are making maintenance much more robust because you can clearly reason about all concurrent operations for any changes you later make to your class. This is best practice for coding, for maintenance, and usually also for performance since it means you can work away at changing the underlying implementation to make it more efficient without having to change anything in the rest of the application. Ideal.
Now on to our usual links to articles, tools, news, talks, blogs. And if you need the tips from this month's articles and talks, as ever they are extracted into this month's tips page.
Java performance tuning related news.
Java performance tuning related tools.
Back to newsletter 202 contents