Reputation: 436
Given the below mentioned code and suppose that we have two different threads thread1,thread2 as well as two different objects p1 and p2 of the class BCell.
If thread1 executes p1.swap(p2)
and thread2 executes p2.swap(p1)
simultaneously what is a possible problem that may occur?
I have already read here and here but it didn't seem to help.
class BCell {
int value;
public synchronized int getValue() {
return value;
}
public synchronized void setValue(int i) {
value=i;
}
public synchronized void swap(BCell x) {
int temp = getValue();
setValue(x.getValue);
x.setValue(temp);
}
}
Upvotes: 2
Views: 174
Reputation: 2999
A possible problem is that both p1 and p2 get the same value. if t1 executes all the way down to setValue(x.getValue());
before t2 has read anything would cause this problem, for example val1 = 5
and val2 = 3
(defining variables based on threads, hope it makes sense)
val1 = 5 val2 = 3
tmp1 = 5
val1 = 3
tmp2 = 3
val2 = 3
val2 = 3
val1 = 3
where thread1 is on the first column and thread2 is in the second.
maybe you could write something like this?
class BCell {
Semaphore writeLock = new Semaphore(1);
int value;
public int getValue() {
return value;
}
public void setValue(int i) throws InterruptedException {
writeLock.acquire();
value=i;
writeLock.release();
}
public void swap(BCell x) throws InterruptedException {
writeLock.acquire();
if(x.writeLock.tryAcquire(10, TimeUnit.MILLISECONDS)) {
int temp = getValue();
setValue(x.getValue());
x.setValue(temp);
x.writeLock.release();
}
else {
writeLock.release();
swap(x);
}
writeLock.release();
}
}
Upvotes: 0
Reputation: 11251
Here is a synchronized instance method:
public synchronized void add(int value){ this.count += value; }
Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized.
A synchronized instance method in Java is synchronized on the instance (object) owning the method.
source of quotation is here.
That means that when you call p1.swap(p2)
it blocks p1
from being used in any other synchronized blocks on that instance until p1.swap(p2)
is finished. So that in your case setValue(x.getValue);
can not be invoked simultaneously.
Upvotes: 2
Reputation: 10717
p1 and p2 are two different instances. therefore, even if the methods were not synchronized no race condition should occur.
Notice that the three are instance methods, and you're synchronizing on the instance lock. Also p1 and p2 are two different instances. Therefore, on the scenario you're proposing synchronizing methods makes no change.
Upvotes: 1