Is a volatile int in Java thread-safe? That is, can it be safely read from and written to without locking?
Is a volatile int in Java thread-safe? That is, can it be safely read
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, you can read from it and write to it safely – but you can’t do anything compound such as incrementing it safely, as that’s a read/modify/write cycle. There’s also the matter of how it interacts with access to other variables.
The precise nature of volatile is frankly confusing (see the memory model section of the JLS for more details) – I would personally generally use
AtomicIntegerinstead, as a simpler way of making sure I get it right.