This content has been marked as final. Show 5 replies
Also, would the same apply if the cache was going to store more Hashmap mappings? For instance, if cache was a HashMap<String, HashMap>() type? Would it still be safe for read-only operations?
If you have immutable data, of any structure at all, it is always thread-safe to read from it. Why wouldn't it be?
This means your MAPPING is safe, if the MAPPING does not change. But if the data being mapped is changing, it might not be safe. We'd have to know more about how you're using it if that's the case.
Edited by: nclow on May 9, 2008 1:55 PM
sorry, forgot to mention that. the data in the cache mapping would consist of sub-mappings, all of which would be initialized once and then never modified again (ie no mapping structure changes and no reassignments or modifications of the end values in the mappings). i'm really just trying to store a snapshot of data at startup and then access it during the program execution (from different threads).
i assumed the data would safe as long as it was only written once but i like to double check when it comes to synchronization issues. like i said i am trying to avoid some of those other classes / methodologies due to locking and bottlenecks. i didn't think they were necessary if access was only ever going to be read only.
Edited by: den2681 on May 9, 2008 10:03 AM
That's right, if all concurrent access is read-only, then your code is thread-safe.
To make sure that no modification can happen later on, you can wrap every HashMap using Collections.unmodifiableMap() after you've set it up. This way your data structure only contains objects that prevent modification.
thanks, i didn't know about unmodifiableMap -- might make a nice touch to prevent future errors.