- can be smaller than a method (can be inside a unsynchronized method), allows holding locks for a smaller time and i.e. to protect only a single field assignment .
- allow to synchronize on other objects than this
Example :
class separateGroups {
private double aVal = 0.0;
private double bVal = 1.1;
protected Object lockA = new Object();
protected Object lockB = new Object();
public double getA(){
synchronized (lockA){
return aVal;
}
}
public void setA(double val){
synchronized (lockA){
aVal=val;
}
}
public double getB(){
synchronized (lockB){
return bVal;
}
}
public void setB(double val){
synchronized (lockB){
bVal=val;
}
}
public void reset(){
synchronized (lockA){
synchronized (lockB){
aVal=bval=0.0;
}
}
}
the reset method changes both values therefore it acquires both locks.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment