Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #25848

Re: boolean and thread safety

From Daniele Futtorovic <da.futt.news@laposte.net.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: boolean and thread safety
Date 2011-02-11 20:24 +0100
Organization A noiseless patient Spider
Message-ID <ij42df$m4v$1@news.eternal-september.org> (permalink)
References <e9ded49c-dfed-4642-83cb-f4b183b6358c@i40g2000yqh.googlegroups.com>

Show all headers | View raw


On 11/02/2011 19:09, raphfrk@gmail.com allegedly wrote:
> Are booleans inherently thread safe?
>
> I am thinking of something like
>
> public class AsyncBoolean {
>
>      boolean value = false;
>
>      public AsyncBoolean(boolean initValue) {
>          value = initValue;
>      }
>
>      public boolean getValue() {
>          return value;
>      }
>
>      public void setValue(boolean value) {
>          value = newValue;
>      }
>
> }
>
> Assuming I define the variable using
>
> 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?
>
> 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.

You're mixing different things here. *Assigning* a boolean value, as in
value = true
is atomic, and hence thread-safe.

But what thread safety is about is only marginally atomicity (because
all assignments save those of double and long variables are atomic). The
main point is what a thread "sees". That is, whether it "sees" the
changes operated by another thread.

With respects to that, no primitive type, no matter how small, is
thread-safe. You'll have to ensure synchronisation of information across
threads. The easiest way to do that, assuming the propagation of the
reference to the "AsyncBoolean" instance is ensured, would be to declare
the "value" field /volatile/. Another way would be to synchronise in the
getter and setter.

Have a look at java.util.concurrent.atomic.AtomicBoolean.

-- 
DF.

Back to comp.lang.java.programmer | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: boolean and thread safety Daniele Futtorovic <da.futt.news@laposte.net.invalid> - 2011-02-11 20:24 +0100
  Re: boolean and thread safety Owen Jacobson <angrybaldguy@gmail.com> - 2011-02-11 22:25 -0500

csiph-web