0

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?

3
  • 3
    That completely depends on exactly what your application does and how. Also, note that HashMap is not thread-safe. Commented Apr 3, 2014 at 2:58
  • See also blog.slaks.net/2013-07-22/thread-safe-data-structures and the rest of that series. Commented 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. Commented Apr 3, 2014 at 3:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Immutable objects can actually make things much easier for a garbage collector, because an immutable reference that's been copied and traced can't be mutated to point to something in from-space. I doubt Java implementations take advantage of this, but functional language implementations (Haskell, ML, etc.) certainly do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.