- when have multiple threads or processes that may want to access the
same data at the same time?? Data corruption!
for the threads case this happens when running on a multi-processor machine
for the processes case, this can happen at any time
SOLUTION: synchorize access to this data
1) Declare method containing access to data as synchrozied
No two threads may be executing synchronized methods of the same object at the same time. |
|
2) Surround code with synchronized statement
Example: say you want to synchronize access to the Object called myDog. Then inside of the method where you access it do the following:
|
Example: Synchronized and Wait/Notice
} Note in the above example, if more that one thread could perform get()s or put()s concurrently then the notify() calls should be changed to notifyAll() calls since a notify from one put()ing thread might happen to wake just another putting thread, which could therefore not make progress - if there is a getting thread then we must make sure that it will be woken up. The while loop and monitor lock will ensure that only the right thread can keep going - the rest will wait again. |