Synchronizing Threads

A program may access the same object from separate concurrent threads. To ensure that only one thread at a time can access an object, we use the synchronized keyword. We can synchronize a method or block of code. When a thread executes a synchronized method or block of code, it places a lock on the associated object. This prevents any other thread from executing any synchronized method that accesses that object.

For example, the SynchronizedSumming class contains two synchronized methods,
add and subtract.

SynchronizedSumming

public class SynchronizedSumming
{
int result;

synchronized void add(int arg1)
{
result = result + arg1;
}

synchronized void subtract(int arg1)
{
result = result - arg1;
}
}


Any thread concurrently executing either of these methods is accessing the same shared SynchronizedSumming object. In particular, the SynchronizedSumming result variable is shared. So we do not want one thread to be executing the add method while another is concurrently executing the subtract method.

As soon as the first thread executes the add method, say, because it is synchronized, a lock is placed on the SynchronizedSumming object. This prevents another thread from executing any synchronized method that accesses the SynchronizedSumming object. In particular, a second thread cannot execute the subtract method. As soon as the first thread completes execution of the add method, the lock on the object is released.

Rather than place a lock on an object for the duration of an entire method, we may be able to isolate critical lines of code that access an object. For example, the add method may perform some time-consuming processing that does not affect the SynchronizedSumming object until the last statement.

We can create a synchronized block around this statement as follows:

void add(int arg1)
{

...
time consuming processing statements
...
synchronized (this)
{
result = result + arg1;
}
}


The this keyword ensures the current object, SynchronizedSumming, is locked. If the
synchronized block accesses another object, object_name, say, that we want to lock, we would use the statement

synchronized (object_name) {

No comments:

Post a Comment