THREADS AND LOCKS
Example: Out of Order Writes
17.11
17.11   Example: Out of Order Writes
This example is similar to that in the preceding section, except that one method
assigns to both variables and the other method reads both variables. Consider a
class that has class variables
a
 and
b
 and methods
to
 and
fro
:
class Simple {
int a = 1, b = 2;
void to() {
a = 3;
b = 4;
}
void fro() {
System.out.println("a= " + a + ", b=" + b);
}
}
Now suppose that two threads are created, and that one thread calls
to
 while the
other thread calls
fro
. What is the required set of actions and what are the order 
ing constraints?
Let us consider the thread that calls
to
. According to the rules, this thread
must perform an
assign
 of
a
 followed by an
assign
 of
b
. That is the bare minimum
required to execute a call to the method
to
. Because there is no synchronization, it
is at the option of the implementation whether or not to
store
 the assigned values
back to main memory! Therefore the thread that calls
fro
 may obtain either
1
 or
3
for the value of
a
, and independently may obtain either
2
 or
4
 for the value of
b
.
Now suppose that
to
 is
synchronized
 but
fro
 is not:
class SynchSimple {
int a = 1, b = 2;
synchronized void to() {
a = 3;
b = 4;
}
void fro() {
System.out.println("a= " + a + ", b=" + b);
}
}
In this case the method
to
 will be forced to
store
 the assigned values back to main
memory before the
unlock
 action at the end of the method. The method
fro
 must,
of course, use
a
 and
b
 (in that order) and so must
load
 values for
a
 and
b
 from
main memory.
413






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