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)?
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).
AtomicBoolean. .
. , .
: AtomicBoolean, .
AtomicBoolean
( ) , , . , , , .
, , .
, , valid = true, ? , , false valid, true. :
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
, ... . , , , , , volatile, , , .
thread-safety - . /. , . , , while() if(), , , :)
https://www.ibm.com/developerworks/java/library/j-jtp06197/ " . :
, , , , , . " . , .
Source: https://habr.com/ru/post/1725552/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1725547/convert-pdf-pages-to-images-with-cocoa&usg=ALkJrhjgnKW3VBuNGKLSkBEMn0WvsjDVuwWindows Microphone Audio Capture Using C - cКак обновить данные в базе данных без удаления старых данных? - php(Ruby on Rails) Page title going as text / javascript when it shouldn't - internet-explorerRails routing is unsustainable with IE - internet-explorerLock your own NSPreferencePane? - objective-cC ++ Boost: Split String - c ++Понимание синхронизированного - javamacos: display windows and discover new windows - objective-cCoredata: import / export of objects from xml - cocoaAll Articles