0

Will there be race condition in situation like this: when one thread reads and other writes in separate methods of course. I'm a beginner to multithreading and concurrency

class counter {
int count = 0;

void increment() {
    count++;
}

int read() {
    return count;
}
}

class voltest {
public static void main(String[] args) {
    final counter c = new counter();
    Runnable r1 = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            c.increment();
        }
    };

    Runnable r2 = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            c.read();
        }
    };

    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);
    t1.start();
    t2.start();
}
}
Sean
  • 60,939
  • 11
  • 97
  • 136
cynic123
  • 29
  • 2

1 Answers1

0

Yes, there's a race condition. Expression like count++ are not atomic - they're classed as read-modify-write expressions, and another thread may access the variable at any point.

Take a look at this link on Java atomics which actually talks about using the increment operator.

Sean
  • 60,939
  • 11
  • 97
  • 136