Synchronization

  • 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

 

synchronized return_type method {

//protected data access here

}

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:

//somewhere inside of a method

synchronized (myDog) {

//All code dealing with myDog

}

 

Note:

public synchronized void foo() { S }

is equivalent to

public void foo() { synchronized (this) { S } }

 

Note: This obtains an exclusive lock on theobject which is maintained for the duration of the following statement block. This allows mutual exclusion for objects (and arrays..can pass arrays or expressions which return object(s) ) which do not have their methods declared to be synchronized.

 

 

 

Example: Synchronized and Wait/Notice

class BetterBuffer {

private Object data;

 

/* synchornized method to Get next data unit. Will put this object's thread into wait mode if no data exists in buffer.*/

public synchronized Object get() {

while (data==null) {

try { wait(); } catch (InterruptedException e) { }

}

Object get_data = data;

data = null;

notify();

return get_data;

}

 

/*synchronized method to put data into the buffer that has a size of 1 unit so, it must wait if their currently already is data in the buffer for it to be removed via the Get method. If this is the case with put this object's thread into wait.*/

public synchronized boolean put(Object put_data) {

while (data!=null) {

try { wait(); } catch (InterruptedException e) { }

}

data = put_data;

notify();

return true;

}

}

 

Note in the above example, that 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.

 

 

© Lynne Grewe 2001