I want to have a flag that could be accessible to read/write from different threads without any problem of dirty values. Is it enough to make it static volatile?
static volatile boolean flag;
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.
No, this is not enough if you need an action like this:
Ideally you want v=0 when you execute the above code, but this is what is really happening (a composite action):
And both the threads will give values of 1 and -1 respectively. Source: Volatile Does Not Mean Atomic!
If you need guaranteed consistent result in a mulithreaded scenario, you should be using Atomic classes in Java as @Eng.Fouad pointed out.
In the case of a boolean too, compare-and-set will be helpful from AtomicBoolean class than using volatile.