• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronizing constructor?  RSS feed

 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Oracle Java tutorials state:


But is not this statement valid only when we have a single processor environment. In multiple processor we
can have multiple threads ACTUALLY executing simultaneously. And if in constructor we are initializing a static variable then
it compounds the problem as now two threads are trying to initialize static variable simultaneously.

Manish
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
manish ghildiyal wrote:
Oracle Java tutorials state:


But is not this statement valid only when we have a single processor environment. In multiple processor we
can have multiple threads ACTUALLY executing simultaneously. And if in constructor we are initializing a static variable then
it compounds the problem as now two threads are trying to initialize static variable simultaneously.


Yes, and no. Yes, I agree that it is possible for the constructor to leak the this reference, before the constructor completes, and hence, there may be a use-case for synchronizing the constructor. However, no, your example isn't a good example of this need. Having two threads, run two different constructors, trying to change a static variable can't be solved by synchronizing the constructor (assuming this feature exists and uses the this object), because the two constructors will have different this references.

Regardless, it is not much of an issue. You can still use synchronized blocks, or use synchronized methods.

Henry
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry, thanks for clarifying the things.

Manish
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!