|Navigate Concurrent Programming topic: )|
In a multi-threaded environment, when more than one thread can access and modify a resource, the outcome could be unpredictable. For example, let's have a counter variable that is incremented by more than one thread.
Beware! Synchronization is an ambiguous term. It doesn't consist of making all threads executing the same code section at the same time. It is the opposite. It prevents any two threads from executing the same code section at the same time. It synchronizes the end of one processing with the beginning of a second processing.
|Code section 1.1: Counter implementation
int counter = 0; ... counter += 1;
The above code is built up by the following sub-operations:
Let's say that two threads need to execute that code, and if the initial value of the
counter variable is zero, we expect after the operations the value to be 2.
|Thread 1||Thread 2|
|Read 0||Read 0|
|Add 1||Add 1|
|Save 1||Save 1|
In the above case Thread 1 operation is lost, because Thread 2 overwrites its value. We'd like Thread 2 to wait until Thread 1 finishes the operation. See below:
|Thread 1||Thread 2|
counter+=1must be executed by one and only one thread at any given time. That is called critical section. During programming, in a multi-threading environment we have to identify all those pieces of code that belongs to a critical section, and make sure that only one thread can execute those codes at any given time. That is called synchronization.
waitmethod on the object. It has to be the same object the thread obtained its object monitor from.
waitmethod only if there is at least one other thread out there who will call the
notifymethod when the resource is available, otherwise the thread will wait for ever, unless a time interval is specified as parameter.
notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resume execution.
finalvoid wait(long time)
notify, but it wakes up all threads that are waiting on this object's monitor.
Objectclass. The thread must have obtained the object-monitor of that object first before calling the wait method. The object monitor is released by the wait method, so it does not block other waiting threads wanting this object-monitor.
Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.