Thread safety of static blocks in Java

前端 未结 4 1670
抹茶落季
抹茶落季 2020-11-28 12:20

Let\'s say I have some Java code:

public class SomeClass {
    static {
        private final double PI = 3.14;
        private final double SOME_CONSTANT =          


        
相关标签:
4条回答
  • 2020-11-28 12:56

    If the first thread hasn't finished initializing SomeClass, the second thread will block.

    This is detailed in the Java Language Specification in section 12.4.2.

    0 讨论(0)
  • 2020-11-28 12:58

    watch out that you dont call code that require the lock for the class being initialized - it will deadlock. see this blog post: http://ramblingabout.wordpress.com/2008/04/10/deadlock-quiz-the-answer/

    0 讨论(0)
  • 2020-11-28 13:02

    Static class initialization is guaranteed to be thread-safe by Java.

    0 讨论(0)
  • 2020-11-28 13:15

    Static block is always thread safe while its getting initialzed. This is the reason use static variable of singleton object as one way of creating singleton object (singelton desing pattern).

    0 讨论(0)
提交回复
热议问题