I have an application which gets objects from a database and stores them in a HashMap roughly once a second. I want the objects to be thread safe as they are accessed from multiple threads, is this a good situation to make the object immutable or would it put a lot of strain on the garbage collector?
-
3That completely depends on exactly what your application does and how. Also, note that HashMap is not thread-safe.SLaks– SLaks2014-04-03 02:58:34 +00:00Commented Apr 3, 2014 at 2:58
-
See also blog.slaks.net/2013-07-22/thread-safe-data-structures and the rest of that series.SLaks– SLaks2014-04-03 02:58:59 +00:00Commented Apr 3, 2014 at 2:58
-
Immutability and thread safety are almost entirely separate topics. You can't have a program that uses ONLY immutables (at the very least you must have mutable references and primitives) and so you can't avoid having to consider that happens if a value is mutated in one thread near to where it might be accessed in another.Hot Licks– Hot Licks2014-04-03 03:08:56 +00:00Commented Apr 3, 2014 at 3:08
1 Answer
Yes, this would be a good situation to make the objects immutable, given that they are value objects constructed from database data. Any time you do not need to change the state of an object is a good time to make that object immutable. Making objects immutable does not generally put extra strain on the garbage collector, as you won't have to make copies of the object for safety when passing it between threads or functions; that can actually mean less strain on the garbage collector.
If the HashMap is also to be used from multiple threads, use a thread safe version, such as ConcurrentHashMap.