Java Reference
In-Depth Information
}
};
EventQueue.invokeLater(r);
}
}
ateGUI()
,
findAll()
,
find()
and
main()
classmethods.Becausemuchofthis
contenthaspreviouslybeendiscussed(in
Chapter7
andearlierinthischapter),I'llfo-
cus on only a few items.
FindAll
is a multithreaded application. As well as the main thread that executes
main()
,
FindAll
'sGUIrunsontheevent-dispatchthread(EDT)andcreatesawork-
erthreadtoexecutethe
findAll()
methodoffoftheEDT,tokeeptheGUIrespons-
ive.
At some point, threads must communicate with shared variables and this is where
lack-of-synchronizationproblemscanarise.I'veeliminatedtheseproblemsbycreating
a single
volatile result
field and using
final
local variables.
The
result
fieldis
volatile
sothattheEDTandworkerthreadcansee
res-
ult
's
String
reference value on multicore or multiprocessor platforms where each
core/processorhasalocalcachedcopyofthisfield.If
result
wasn't
volatile
,the
EDT might not see the reference to a new
String
object assigned to
result
when
findAll()
findsamatch,andwouldprobablyappendacopyofthepreviouslyfound
match to the textarea. (This isn't a problem on single processor/single core platforms.)
Althoughthisrationalealsoholdsforthe
startDir
and
srchText
localvariables,
they're declared
final
instead of
volatile
. They need to be declared
final
so that they can be accessed from the anonymous class that implements
java.lang.Runnable
in the search button's action listener.
chronization.Asaresult,
volatile
isn'trequiredfora
final
field,andyoucannot
declareafieldtobe
volatile
and
final
atthesametime.(A
final
fieldcanbe
safely accessed but not necessarily the objects to which
final
reference fields refer.
Because
String
objectsareimmutable,therewouldbenoproblemifIcalled
String
methods on
startDir
,
srchText
, and
result
.)
Thesearchbutton'sactionlistenerdeclaresarunnablewithinarunnable,andthecode
probably looks complicated. The following sequence of steps explains how this code
works: