Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #25586
| From | Lew <noone@lewscanon.com> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: boolean and thread safety |
| Date | 2011-02-11 17:46 -0500 |
| Organization | albasani.net |
| Message-ID | <ij4e6i$4k3$1@news.albasani.net> (permalink) |
| References | <e9ded49c-dfed-4642-83cb-f4b183b6358c@i40g2000yqh.googlegroups.com> <ij40vq$55r$1@news.eternal-september.org> |
raphfrk@gmail.com wrote: >> Are booleans inherently thread safe? Have you read the tutorials on concurrent programming in Java? Have you read /Java Concurrency in Practice/ by Brian Goetz, et al.? Any of the concurrency articles in IBM's Developerworks/Java site? You should. markspace wrote: > No. raphfrk@gmail.com wrote: >> final AsyncBoolean varName = new AsyncBoolean(true); >> >> does this in effect auto-sync, since you can't partially read a byte >> and even if you could it is a boolean anyway? markspace wrote: > No. There are more than one types of memory in a modern system. Cache and > registers come into play. So you can't just "read a byte" because you don't > know where you are reading from. One byte could be in memory while a different > thread could have that same byte in cache or in a register. raphfrk@gmail.com wrote: >> Since it is declared as final, the reference can't change, so I could >> then call varName.setValue(someValue) and varName.getValue() from >> threads without the need for syncing. That only protects against changing the reference, not the contents of the item pointed to. So you still need to synch. Note that 'varName.getValue()' doesn't change the reference, but does change the object. It is changes to the *object* that you must guard here. markspace wrote: > The final declaration is only thread safe for instance variables, after its and only for changing the *variable* contents. For reference variables, that doesn't help against changes to the *object* contents. Reference variables are pointers. > constructor has finished. Anything else requires more explicit synchronization. > > For this specific example you probably want to declare your boolean as > volatile. That removes the need for final (in this case) and also removes the > need for any other synchronization (in this case). Also, on i86 archetecture, > volatile is very light-weight and "free" for reads. As the study material on Java concurrency explains. -- Lew Ceci n'est pas une fenĂȘtre. .___________. |###] | [###| |##/ | *\##| |#/ * | \#| |#----|----#| || | * || |o * | o| |_____|_____| |===========|
Back to comp.lang.java.programmer | Previous | Next | Find similar
Re: boolean and thread safety Lew <noone@lewscanon.com> - 2011-02-11 17:46 -0500
csiph-web