Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 5: Writing Classes
Start Practice TestPractice Test
About Exam
hard Solved by 1 students

Java Thread Race Condition

Mark
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|