1

I noticed interesting behaviour:

I can write

class My {
     public My(){
        synchronized(this){
            // code
        }

    }  
}

but I cannot write

class My {
         public synchronized My(){
                // code
            }

        }  
    }

I thought that both constructions works identically terms java API.

Please clarify this misunderstanding.

laaposto
  • 11,835
  • 15
  • 54
  • 71
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • 2
    possible duplicate of [Why can't Java constructors be synchronized?](http://stackoverflow.com/questions/4880168/why-cant-java-constructors-be-synchronized) – rethab Apr 28 '14 at 09:39

2 Answers2

2

In the first case, the object is almost created, only the body of the Constructor need to executed.

But, in the second case, there won't any object to synchronize.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

It is impossible situation that two Threads will create same object !

Thus synchronized modificator hasn't sense for constructor.

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710