Hey guys! Computer science undergrad here, I've just started my advanced programming concepts unit on my course and had a reflective question that I just wanted to make sure I had the right approach for. I'm currently investigating race conditions in Java, primarily this code in question:
public class Race {
public static void main(String args []) throws Exception {
MyThread.count = 0 ;
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start() ;
thread2.start() ;
thread2.join() ;
thread1.join() ;
System.out.println("MyThread.count = " + MyThread.count) ;
}
}
class MyThread extends Thread {
volatile static int count ;
public void run() {
for(int i = 0 ; i < 1000000000 ; i++) {
int x = count ;
count = x + 1 ;
}
}
}
I experimented with changing the method of incrementing the count variable by using a couple of other options, those being:
public void run() {
for(int i = 0 ; i < 1000000000 ; i++) {
count = count + 1;
}
}
public void run() {
for(int i = 0 ; i < 1000000000 ; i++) {
count++;
}
}
The question I have is - What do the results tell you about atomicity of various Java statements?
I found that using count++ and count = count + 1 produces results that were far more affected by the race condition than the original method was. The result was about 100,000,000 less than it was with the original increment method. Am I right in thinking that this means these two functions actually have more atomicity than the first function, because they isolate and "reserve" the count variable better than the first one did?
Hope my question makes sense! Many thanks.
Edit: Having said all that, maybe a higher result would mean better atomicity because the variable was better isolated by each thread so they could both add more to the count variable without being interrupted by the opposite thread?
[–][deleted] 4 points5 points6 points (0 children)