Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which one of the following statements about sharing an immutable object between threads is true?

  • A.A class with only final fields, set once in the constructor, is safe to share without synchronization.
  • B.A class with only final fields still needs its fields declared volatile to be shared safely.
  • C.A class with only final fields must still be published inside a synchronized block.
  • D.Immutability makes no difference to thread safety; every shared object needs a lock.

Answer: A

An immutable object has no state to change, so there is no interleaving to protect against, and the memory model guarantees that correctly constructed final fields are visible to any thread that sees the reference. The caveat is construction: the object must not let this escape before it is finished.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.