THREADS AND LOCKS
Example: Possible Swap
17.10
lock an object before accessing any of its instance variables, for example; syn
chronized methods are a convenient way to follow this convention. In other appli
cations, it may suffice to use a single lock to synchronize access to a large
collection of objects.
If a thread uses a particular shared variable only after locking a particular lock
and before the corresponding unlocking of that same lock, then the thread will
read the shared value of that variable from main memory after the
lock
action, if
necessary, and will copy back to main memory the value most recently assigned to
that variable before the
unlock
action. This, in conjunction with the mutual exclu
sion rules for locks, suffices to guarantee that values are correctly transmitted
from one thread to another through shared variables.
The rules for
volatile
variables effectively require that main memory be
touched exactly once for each
use
or
assign
of a
volatile
variable by a thread,
and that main memory be touched in exactly the order dictated by the thread exe
cution semantics. However, such memory actions are not ordered with respect to
read
and
write
actions on nonvolatile variables.
17.10 Example: Possible Swap
Consider a class that has class variables
a
and
b
and methods
hither
and
yon
:
class Sample {
int a = 1, b = 2;
void hither() {
a = b;
}
void yon() {
b = a;
}
}
Now suppose that two threads are created, and that one thread calls
hither
while
the other thread calls
yon
. What is the required set of actions and what are the
ordering constraints?
Let us consider the thread that calls
hither
. According to the rules, this
thread must perform an
use
of
b
followed by an
assign
of
a
. That is the bare mini
mum required to execute a call to the method
hither
.
Now, the first action on variable
b
by the thread cannot be
use
. But it may be
assign
or
load
. An
assign
to
b
cannot occur because the program text does not call
for such an
assign
action, so a
load
of
b
is required. This
load
action by the thread
in turn requires a preceding
read
action for
b
by the main memory.
409
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved