Constructor synchronization in Java

前端 未结 6 1105
执笔经年
执笔经年 2020-11-28 09:17

Someone somewhere told me that Java constructors are synchronized so that it can\'t be accessed concurrently during construction, and I was wondering: if I have a constructo

6条回答
  •  情歌与酒
    2020-11-28 09:53

    It's unsafe. There are no additional synchronization in JVM. You can do something like this:

    public class Test {
        private final Object lock = new Object();
        public Test() {
            synchronized (lock) {
                // your improper object reference publication
                // long initialization
            }
        }
    
        public void doSomething() {
            synchronized (lock) {
                // do something
            }
        }
    }
    

提交回复
热议问题