Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does access/write to Boolean object needs synchronization

This may seem a very silly question. Consider this:

I have a simple Boolean object with a getter and a setter. Now both of the methods are called from a lot of threads very frequently.

  1. Do I need to have a synchronization for this boolean?
  2. Also are Boolean assignments atomic operations?

[UPDATE]: I know about Atomic Boolean already. I already have a lot of varied solutions, But I was specifically looking for answers and justification of answers for the above 2 question.

like image 946
Suraj Chandran Avatar asked Apr 16 '10 03:04

Suraj Chandran


2 Answers

No, Boolean access is NOT atomic (on the level of machine code), although it does take "only 1 operation in Java".

Therefore, yes, you do need synchronization for Boolean.

Please see slides 4-6 of this presentation for code examples.

On a related note, you should not synchronize on a Boolean

like image 176
DVK Avatar answered Sep 20 '22 15:09

DVK


  1. Yes. But if it's a flag that is written from one thread only and you want to ensure visibility to all threads, then a cheap alternative is using volatile.

  2. Yes - even though the internal representation of the object (i.e. the actual boolean flag inside the Boolean wrapper) were 64 bit and it could therefore get "split" in a concurrent situation, a boolean can only have one of the two values, right? So plain assignments (get or set) are atomic, but if you're doing anything else (like check-then-act), for instance x = !x, then it's of course not atomic unless synchronized.

like image 43
Joonas Pulakka Avatar answered Sep 23 '22 15:09

Joonas Pulakka