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

Discussion

Thread safety of a static initialiser - which of the following is true?

  • A.A static initialiser must be declared synchronized to be safe under concurrent use.
  • B.Static initialisers are skipped entirely unless the class is loaded from the main thread.
  • C.Class initialisation is performed under a lock by the JVM.
  • D.A static initialiser may run more than once if several threads use the class simultaneously.

Answer: C

The JVM synchronises class initialisation, so however many threads race to use a class first, its static initialiser runs exactly once and its effects are visible to all of them. This is what makes the holder idiom a correct lazy singleton without any explicit locking.

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

Post your comment

Please log in or register to post a comment.