| Quiz | Posted | Given in class | ||
|---|---|---|---|---|
| 6 | Feb | 11 | Feb | |
Consider the following class which you are not allowed to modify
public class Num {
private int n;
public Num(int n) { setN(n); }
public void setN(int n) { this.n = n; }
public int getN() { return n; }
}
and suppose we have two instances of Num:
Num num1 = new Num(0); Num num2 = new Num(1);
num1.setN(num1.getN() + 1);
Num class. Write code to
execute the above statement atomically.
Num class.
Write code to swap the contents of num1 and num2
atomically.
You must be holding a lock on
both objects for this to work.
public class GenID {
private static int nextID = 0;
private int myID;
public GenID() {
myID = nextID;
nextID = nextID + 1;
}
public void getID() { return myID; }
}