Suppose that there are many threads that call the method m(int i) and change the value of the array in position i. Is the following code correct, or is there a race condition?
public class A{
private int []a =new int[N];
private Semaphore[] s=new Semaphore[N];
public A(){
for(int i =0 ; i<N ; i++)
s[i]=new Semaphore(1);
}
public void m(int i){
s[i].acquire();
a[i]++;
s[i].release();
}
}
The code is correct, I see no race condition although both
aandsshould be madefinal. You should also use a try/finally every time you use locks that need to be acquired and released:But, for updating an array, the idea of individual locks per item is very unnecessary. A single lock would be just as appropriate since the major cost is the memory updating and the other native synchronization. This said, if the actual operation is not a
int ++then you are warranted in using aSemaphoreor otherLockobject.But for simple operations, something like the following is fine:
If you are really worried about the blocking then an array of
AtomicIntegeris another possibility but even this feels like overkill unless a profiler tells you otherwise.Edit:
I just wrote a quick stupid test program that compares a single
synchronizedlock, asynchronizedon an array of locks,AtomicIntegerarray, andSemaphorearray. Here are the results:synchronizedon theint[]10617mssynchronizedon an array ofObject[]1827msAtomicIntegerarray 1414msSemaphorearray 3211msBut, the kicker is that this is with 10 threads each doing 10 million iterations. Sure it is faster but unless you are truly doing millions of iterations, you won’t see any noticeable performance improvement in your application. This is the definition of “premature optimization”. You will be paying for code complexity, increasing the likelihood of bugs, adding debugging time, increasing maintenance costs, etc.. To quote Knuth:
Now, as the OP implies in comments, the
i++is not the real operation that s/he is protecting. If the increment is a lot more time consuming (i.e. if the blocking is increased), then the array of locks will be required.