Java Reference
In-Depth Information
Whenafieldisdeclared volatile ,itcannotalsobedeclared final .Ifyou'rede-
pendingonthe semantics (meaning)ofvolatility,youstillgetthosefroma final field.
In his “Java theory and practice: Fixing the Java Memory Model, Part 2” article ( ht-
tp://www.ibm.com/developerworks/library/j-jtp03304/ ) , Brian
Goetzhasthistosayaboutthisissue:“ThenewJMM[JavaMemoryModel]alsoseeks
toprovideanewguaranteeofinitializationsafety—thataslongasanobjectisproperly
constructed(meaningthatareferencetotheobjectisnotpublishedbeforetheconstruct-
or has completed), then all threads will see the values for its final fields that were set
in its constructor, regardless of whether or not synchronization is used to pass the ref-
erencefromonethreadtoanother.Further,anyvariablesthatcanbereachedthrougha
final field of a properly constructed object, such as fields of an object referenced by a
finalfield,arealsoguaranteedtobevisibletootherthreadsaswell.Thismeansthatifa
finalfieldcontainsareferenceto,say,a LinkedList ,inadditiontothecorrectvalue
ofthereferencebeingvisibletootherthreads,alsothecontentsofthat LinkedList at
constructiontimewouldbevisibletootherthreadswithoutsynchronization.Theresult
isasignificantstrengtheningofthemeaningof final —thatfinalfieldscanbesafely
accessed without synchronization, and that compilers can assume that final fields will
not change and can therefore optimize away multiple fetches.”
Caution Youshouldonlyuse volatile inthecontextofthreadcommunication.
Also,youcanonlyusethisreservedwordinthecontextoffielddeclarations.Although
youcandeclare double and long fields volatile ,youshouldavoiddoingsoon
32-bit JVMs because it takes two operations to access a double or long variable's
value, and mutual exclusion via synchronization is required to access their values
safely.
Object 's wait() , notify() , and notifyAll() methods support a form of
threadcommunicationwhereathreadvoluntarilywaitsforsome condition (aprerequis-
ite for continued execution) to arise, at which time another thread notifies the waiting
threadthatitcancontinue. wait() causesitscallingthreadtowaitonanobject'smon-
itor, and notify() and notifyAll() wake up one or all threads waiting on the
monitor.
Caution Becausethe wait() , notify() ,and notifyAll() methodsdepend
onalock,theycannotbecalledfromoutsideofasynchronizedmethodorsynchronized
block. If you fail to heed this warning, you will encounter a thrown instance of the
java.lang.IllegalMonitorStateException class. Also,athreadthathas
acquired a lock releases this lock when it calls one of Object 's wait() methods.
Search WWH ::




Custom Search