• Post Reply Bookmark Topic Watch Topic
  • New Topic

Quick question - visibility

 
Des Robin
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

Busy reading "Java concurrency in practice" and writing test code while trying out some ideas (on chapter 4 and discovering all the issues around visibility i.e. using volatile, final et. al.). Raised a question for me - am I correct in assuming that extending Thread or implementing Runnable ensures the data / objects composing my object will be made automatically visible (not thread-safe, just visible)? I'm asking because I have seen a awful lot of code in books doing this sans volatile, final, locking etc.

Thanks.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

There are two concepts here Thread the java object representing an OS thread and the thread of execution (OS thread itself). Visibility issues are between OS threads of execution what this means is say as an example the java thread class the constructor will likely not be called from the same thread as the run method so you have potential for visibility issues here i.e. anywhere more than one thread reads and write to the same variable you have to be careful to establish happens before ordering

If you extend Java Thread with your own code your not making the problem better or worse per se, it's what you do with your new code that is the issue i.e. in which thread of execution you call it in/ how you are synchronized etc. You might be better posting some examples your interested in.
 
Des Robin
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chris

Thanks for the reply. In JCIP (page 50 and 51) it makes reference to a class defined as follows:



In the above example it is possible for assertSanity() to have n fail to be equal to n (on being called by a second thread) because the first time n is retrieved it is stale (i.e. init'd to 0 by the superclass) while the second time it now refers to an updated value (init'd to 42 by the constructor invocation).

Anyway this started my mind wandering... and to answer my own question; no the variables are not made visible (found an example in JCIP).

Thanks for your feedback.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!