When a variable or Object
needs to be accessed
from more than one thread, there are two approaches, each of which
has a slightly different impact on performance:
Marking a variable
as volatile
is the least restrictive approach and
can have very high performance because no Thread
is
blocked. Any Thread
can read or write a volatile
variable at any time. This is useful when you want to avoid blocking
the Thread
. Here you have to pay attention to execution
order. In multi-core phones, volatile
variables are
stored in slightly slower cache memory (not the local core cache)
than non- variables
, but this is not an issue on
Series 40 as there are currently no multi-core Series 40 phones. Thus volatile
is essentially “free” but serves as a good practice
reminder to the programmer how this variable is used, and provides
forward compatibility to the unknowable future of your code.
synchronised
blocks similarly restrict access to a variable, Object
, or section of code as sensitive such that only one Thread
may enter the synchronised
sections at any one
time. The advantage this approach has over volatile
is that you can change several variables at the same time as one
atomic operation. For example, when updating firstName
and lastName
from “Arnold Schwarzenegger” to “Sophie
Marceau”, do so within a synchronised
block to avoid
briefly exposing the transitional state “Sophie Schwarzenegger” to
other threads.
One common mistake worth noting is that if you ever access a variable
which is at any point visible to more than one thread within a synchronised
block, you can only access that variable for
reading or writing with synchronised
blocks unless
for unusual reasons you also mark the variable as volatile
. Spend some time thinking about the ways in which reading and writing
a synchronised
variable in unsynchronised code can
go wrong, and you eventually conclude that there are three types of
variables when it comes to multi-threaded code: