> I noticed later what I guess is another problem in my code: the
> "value" field should be volatile, right?
If you don't use an STM you need to make sure that you apply enough
synchronization, so a volatile could be sufficient for that.
With an STM, the field is managed by an STM and the STM has to make
sure that it applies enough synchronization. So no volatile or
synchronized needed on managed fields, this has all become task of the
STM.
Multiverse also guarantees a happens before relation between a start
and commit, so all changes made by a commit will be visible in each
following start. So also nothing to worry about.
PS:
I think something like this should work:
@AtomicObject
public class Unsafe {
int value=0;
final Random r=new Random(System.currentTimeMillis());
public void setValue(int i){value=i;}
public int getValue(){return value;}
public void inc(){
int tmp=getValue();
setValue(tmp+1);
}
static class Changer extends Thread{
final Unsafe unsafe;
Changer(Unsafe unsafe){
this.unsafe = unsafe;
}
public void run(){
for (int i = 0; i < 1000; i++) {
//System.out.println("inc");
inc();
}
}
}
public static void main(String[] args) {
Unsafe unsafe = new Unsafe();
System.out.println("start");
Changer c1=new Changer(unsafe);
Changer c2=new Changer(unsafe);
c1.start();
c2.start();
try {
c1.join();
} catch (InterruptedException ex) {ex.printStackTrace();}
try {
c2.join();
} catch (InterruptedException ex) {ex.printStackTrace();}
System.out.println(unsafe.getValue());
}
}