Volatile boolean

If I have volatile boolean (is it valid correctly), is the following code snippet safe for threads in Java?

if (valid)
  return;
valid = true;

Or do I need to synchronize, since valid is true only if it is false (hence, the valid value depends on its current value)?

+3
source share
7 answers

This needs to be synchronized, because if one thread evaluates the value as false, and then pauses execution before assignment, then another comes and also checks as false, before setting true to true, you will have two code streams, the following here (which presumably you don't want).

+8

AtomicBoolean. .

+5

. , .

+4

: AtomicBoolean, .

( ) , , . , , , .

+2

, , .

, , valid = true, ? , , false valid, true. :

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;

, valid = true ... . , , volatile , , . , valid .

, ... . , , , , , volatile, , , .

+1

thread-safety - . /. , . , , while() if(), , , :)

+1
0

Source: https://habr.com/ru/post/1725552/


All Articles