Skip to content

Thread Safety

Yuki Kimoto edited this page Feb 23, 2024 · 13 revisions

Requirements to make a class immutable.

  • All class variables are private.
  • All class variables are immutable.
  • No methods other than the INIT block to set class variables.
  • the INIT block is not called except in the INIT block.
  • All fields are private.
  • All fields are immutable.
  • No methods other than the constructor to set fields.

Do not assume that a class is immutable unless the class documentation says so.

Requirements to make the program thread-safe.

  • The all methods in an immutable class is thread-safe.
  • The methods that update class variables are not thread-safe. A lock is needed to make the method thread-safe.
  • The methods that update fields of the object created by other threds are not thread-safe. A lock is needed to make the method thread-safe.