THREADS AND LOCKS
Example: Possible Swap
17.10
write
a
read
a
,
read
b
write
b
 (then
ha=2
,
hb=2
,
ma=2
,
mb=2
,
ya=2
,
yb=2
)
read
a
write
a
,
write
b
read
b
 (then
ha=1
,
hb=1
,
ma=1
,
mb=1
,
ya=1
,
yb=1
)
read
a
write
a
,
read
b
write
b
 (then
ha=2
,
hb=2
,
ma=2
,
mb=1
,
ya=1
,
yb=1
)
Thus the net result might be that, in main memory,
b
 is copied into
a
,
a
 is copied
into
b
, or the values of
a
 and
b
 are swapped; moreover, the working copies of the
variables might or might not agree. It would be incorrect, of course, to assume that
any one of these outcomes is more likely than another. This is one place in which
the behavior of a Java program is necessarily timing dependent.
Of course, an implementation might also choose not to perform the
store
 and
write
 actions, or only one of the two pairs, leading to yet other possible results.
Now suppose that we modify the example to use
synchronized
 methods:
class SynchSample {
int a = 1, b = 2;
synchronized void hither() {
a = b;
}
synchronized void yon() {
b = a;
}
}
Let us again consider the thread that calls
hither
. According to the rules, this
thread must perform a
lock
 action (on the class object for class
SynchSample
)
before the body of method
hither
 is executed. This is followed by a
use
 of
b
 and
then an
assign
 of
a
. Finally, an
unlock
 action on the class object must be per 
formed after the body of method
hither
 completes. That is the bare minimum
required to execute a call to the method
hither
.
As before, a
load
 of
b
 is required, which in turn requires a preceding
read
action for
b
 by the main memory. Because the
load
 follows the
lock
 action, the
corresponding
read
 must also follow the
lock
 action.
Because an
unlock
 action follows the
assign
 of
a
, a
store
 action on
a
 is man 
datory, which in turn requires a following
write
 action for
a
 by the main memory.
The
write
 must precede the
unlock
 action.
The situation for the thread that calls
yon
 is similar, but with the roles of
a
 and
b
 exchanged.
411






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

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