II. Mutual exclusion of critical sections
Mutual exclusion can solve the problems of synchronization 1, 3 and 5 which are in the list of the general problems.
Here is a sample program that does not meet the security, if multiple threads can simultaneously access:
Code:
class Lsttab {
private String[] t = new String[50];
private int ind = 0;
void adds (Strings)
{
t [ind] = s;
ind + +;
}
}
This program, as you guessed, allows a list of Strings using a table.
Code:
void adds (Strings)
{
tab [ind] = s; / / (a1)
ind + +; / / (a2)
}
And / Or
Code:
void adds (Strings)
{
tab [ind] = s; / / (b1)
ind + +; / / (b2)
}
The function adds is called critical section. Several critical sections dependent should never execute their code simultaneously (by several different threads). It is said they are mutual exclusion. In the previous example, adds was mutually exclusive with itself, but of course we can imagine it will also be mutually exclusive with the function removes.
To implement the mutual exclusion, we must use Locks. When a thread enters a critical section, it requests the lock. If it gets its, it can then execute the code. If it does not get it, because another thread has already taken, then it is blocked waiting to receive it. It is possible to use a potentially infinite number of locks, and then make specific mutual exclusion.
II.A - Synchronized Keyword:
To achieve this in Java, the easiest method is to use the keyword synchronized.
Here's how it is used:
Code:
synchronized(Obj)
{
/ / critical section
}
Obj represents a lock that can be an Java Object. Beware though, it is better to use references reported Final. To be sure that the reference to the object is not changed, in fact, the scenario below does not work, because when multiple threads reach the synchronized block, the variable mlst does not always reference the same object, and therefore is not always the same lock.
Code:
synchronized(mlst)
{
mlst = new ArrayList <String>();
}
Special case: When the object is lock for synchronization and it includes all the code of a method, you can put the keyword synchronized in the method signature. The two codes below are strictly equivalent:
Code:
void method ()
{
synchronized(this) {
/ / critical section
}
}
And
Code:
synchronized void method ()
{
/ / critical section
}
II.B - Package java.util.concurrent.locks:
Another method for making locks, appeared in Java 1.5. At first sight it may seem complicated, but it is also more powerful in the sense that it can do things that the keyword synchronized does not.
Here's how to use it:
Code:
Lock lc = newReentrantLock ();
lc.lock ();
try {
/ / critical section
} finally
{
lc.unlock ();
}
To compare this method with the previous lc.lock () and lc.unlock () correspond to the beginning and end of block synchronized. However, if you wish to mutual exclusion as simple as those examples presented here, I advise you to use synchronized And to reserve this method for special cases.
Bookmarks