Blogs / Tech Blog

Tips and tricks for immutable objects

IBM DeveloperWorks has a good article on tips and tricks when creating immutable objects. Everyone knows that a good way to enforce thread safety without locks or explicit customization is to use immutable objects. This article covers some of the tricky parts of doing that:

  • You have to remember to make the members final.
  • You can cache state but not compute it in the constructor if you make it a write-once field. (Which, interestingly, does not mean it’s only written once. It means that it’s only ever written with one value.)
  • Write-once fields are guaranteed for both primitives and objects, but there’s no guarantee with objects that you see the same object reference between accesses.

Read the whole thing.

Other Blogs