Java Reference
In-Depth Information
Fig. 3.3 Example output from a multithreaded server and two connected clients
Fig. 3.4 Two threads
attempting to update the same
variable at the same time
sum
thread1
thread2
23
add 5
add 19
operations: read the current value of sum , create a copy of it, add the appropriate
amount to this copy and then write the new value back. The fi nal value from the
two original update operations, of course, should be 47 (=23 + 5 + 19). However, if
both reads occur before a write takes place, then one update will overwrite the
other and the result will be either 28 (=23 + 5) or 42 (=23 + 19). The problem is
that the sub-operations from the two updates may overlap each other.
In order to avoid this problem in Java, we can require a thread to obtain a lock on
the object that is to be updated. Only the thread that has obtained the lock may then
 
Search WWH ::




Custom Search