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,377
  • 15
  • 52
  • 68
gstackoverflow
  • 34,819
  • 98
  • 304
  • 641
  • 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
  • 29,154
  • 11
  • 70
  • 102
0

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

Thus synchronized modificator hasn't sense for constructor.

gstackoverflow
  • 34,819
  • 98
  • 304
  • 641