• Post Reply Bookmark Topic Watch Topic
  • New Topic

How is this a safe publication?  RSS feed

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

I am going through the following url
Java theory and practice - IBM

Under the section, What do you mean by "publish"? , the following code is written



1) The respected author says that it is a safe publication. I fail to understand why ? The contention in my mind is that what if the compiler or processor or cache reorders

statement in the constructor and puts it as the first statement in the constructor. Won't the inner class MyThread be able to see a partially constructed object ?
 
Stephan van Hulst
Saloon Keeper
Posts: 7722
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, but it's a private inner class right? You can trust it not to abuse the reference.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well its written by Brian Goetz who is usually right, however its appears to be written 10 years ago and before JSR133 so I guess Brian's advice would be not to read it and look up something more relevant :-)

I think that the example has issues and I suspect if he rewrote it today we'd see final being used as he hints at the end.

The start method looks unsafe for several reasons, he appears to be trying to demo the equivalent of

A call to start() on a thread happens-before any actions in the started thread.
in the new memory model.

... so if a thread constructs an object and then it starts a thread that uses that object , that has happens before ordering (at the point of starting)... fine I can see where he's going) ...

... but there is no guarantee in his example the thread that constructs the object calls the start as well but then if that's allowable you have a much simpler problem(ie just reading a non final field thread with no happens before ordering ) ..... by not having the start in the ctr (very good idea to not have it there off course) he's given himself another problem in that you can't tie the ctr and start to the same thread. It's possible I've missed something but can't see it, a bit confusing at best.


The quick answer I think this article is redundant given its age and if I'm sure would at least use final if written today, which I think he hints at.
 
Gagan Sabharwal
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks people.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!