Your code is not threadsafe, but it really depends on your other code whether or not it is safe to do that.
Do you require that the code following valid = true
only be executed once by a single thread? If so, then your code is not safe because any number of threads can read a false
value of valid
, and then end up setting it to true
. For example:
if (valid)
return;
// Imagine every single one of your threads stops and blocks here.
// They will all wake up again and set valid to true and then
// execute the code to follow.
valid = true;
But if you just want to guarantee that the code after valid = true
is executed at most one time by any thread... then what you have is fine. But if that's the behavior you require I would achieve that by other means, because using volatile
in that case will just look like you don't know what you're doing. For example, you could just not share the valid
variable across threads, and allow each thread to just execute the code once.
Also, when in doubt while reasoning about synchronization and volatile... just use synchronization. It is usually more clear, and will get you everything you wanted from using volatile
, except it will be easier to reason how the code works.