Happens before between threads and atomic variable Part 2

42
November 19, 2018, at 03:40 AM

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?

Answer 1

There is a possibility of thread1 writing to t1 after thread2 has executed if (t1 == null ) before reaching corresponding assert statement or vice versa.

If statement and assert following it should be executed within a synchronized context.

READ ALSO
Im not able to figure out how to complete this ques in min time [on hold]

Im not able to figure out how to complete this ques in min time [on hold]

There are n people and n tasksevery person can complete every task with different times

39
Java Connect To SqlServer Database

Java Connect To SqlServer Database

I am trying to connect to the SQL Server database using Eclipse but it's giving me the error:

33
FullCalendar: not showing Google Calendar events

FullCalendar: not showing Google Calendar events

I have an event set up for the 24th November, but even after adding all the scripts/CSS, the calendar initialises but no dice showing the event

25
Home Page Shows as URL in Browser Tab, how do I set my blog title as the tab text?

Home Page Shows as URL in Browser Tab, how do I set my blog title as the tab text?

I was trying to change it so that my blog title appears after the page title for postsMy normal posts are now OK, but the homepage shows the URL in the browser tab, instead of my blog title

23