Why can't Java constructors be synchronized?

前端 未结 9 1468
甜味超标
甜味超标 2020-11-29 18:20

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating

相关标签:
9条回答
  • 2020-11-29 19:01

    Note that constructors cannot be synchronized — using the synchronizedkeyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

    0 讨论(0)
  • 2020-11-29 19:05

    The question has been raised on a discussion list used by the writers of the Java concurrent API and the Java Memory Model. Several answers were given, in particular Hans Boehm replied:

    Some of us (myself included IIRC) actually argued during the Java memory model deliberations that synchronized constructors should be allowed. Now I could go either way on it. Client code shouldn't use races to communicate the reference, so it shouldn't matter. But if you don't trust the clients of [your class], I think synchronized constructors could possibly be useful. And that was much of the reasoning behind final field semantics. [...] As David said, you can use synchronized blocks.

    0 讨论(0)
  • 2020-11-29 19:07

    The following code can achieve the expected result for synchronized constructor.

    public class SynchronisedConstructor implements Runnable {
    
        private int myInt;
    
        /*synchronized*/ static {
            System.out.println("Within static block");
        }
    
        public SynchronisedConstructor(){
            super();
            synchronized(this){
                System.out.println("Within sync block in constructor");
                myInt = 3;
            }
        }
    
        @Override
        public void run() {
            print();
        }
    
        public synchronized void print() {
            System.out.println(Thread.currentThread().getName());
            System.out.println(myInt);
        }
    
        public static void main(String[] args) {
    
            SynchronisedConstructor sc = new SynchronisedConstructor();
    
            Thread t1 = new Thread(sc);
            t1.setName("t1");
            Thread t2 = new Thread(sc);
            t2.setName("t2");
    
            t1.start();
            t2.start();
        }
    }
    
    0 讨论(0)
提交回复
热议问题