Java Thread Race Condition
Consider the following code. What is the primary concurrency issue that occurs when two threads concurrently execute the increment() method on the same Counter object?
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) counter.increment(); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) counter.increment(); });
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount());
}
}
A
Race condition due to non-synchronized access to the shared variable ‘count’.
B
Deadlock caused by mutual waiting between threads.
C
Incorrect sequential execution due to thread scheduling constraints.
D
Memory leak caused by improper object disposal.
Question Leaderboard
Not enough data yet to show leaderboard.
