Java Thread Race Condition
In the code above, what is the primary concurrency issue that may occur when two threads call increment() concurrently?
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
Deadlock caused by mutual waiting between threads.
B
Race condition due to non-synchronized access to the shared variable ‘count’.
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.
APFIVE