Since answer to Happens before between threads and atomic variable was that the asserts don't hold, I need an alternate implementation. Thread1 and Thread2 each update Integers t1 and t2 respectively. Once they are updated no other updates occur to t1 or t2. The values assigned to t1 and t2 come from a common counter which gets incremented after each assignment. I need to ensure the following asserts are true;
int cnt=0;
ReentrantLock lock = new ReentrantLock();
volatile Integer t1=null;
volatile Integer t2=null;
//Thread1
lock.lock();
try{t1=cnt++;}finally{lock.unlock();}
if(t2 == null){
assert t2==null || t2>t1;
}
//Thread2
lock.lock();
try{t2=cnt++;}finally{lock.unlock();}
if(t1==null){
assert t1==null || t1>t2;
}
The question is do the asserts hold? Is volatile required on t1 and t2 as shown? Is there a better/correct way to accomplish this?