Practice mode Java

Why does declaring an int field count as volatile fail to make count++ thread-safe in Java?

Correct answer C. The increment is a separate read, change and write

Explanation

Volatile guarantees that reads see the most recent write, but count++ performs a read, an addition and a write as three steps. Two threads can read the same value and lose one update. Making the whole operation atomic needs a synchronized block or a class such as AtomicInteger, whose incrementAndGet method is indivisible.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.