0

If I have a class holding a private boolean made public by a setter and getter method , would I have to set those methods as synchronized if I want to read and write to that boolean from different threads?

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
  • Do you have to? No. But you may want to. For that matter, synchronizing the getter and setter may not be sufficient to protect you, depending on what other data is being accessed by both threads. You really need to give us a lot more info on what each thread is doing to answer well. – Gabe Sechan Mar 31 '13 at 22:37

3 Answers3

3

Synchronizing access of a simple value is often unnecessary. Generally all you need is to mark it volatile which is less restrictive and more informative.

It all really depends a lot on how you access the value.

In some cases using an AtomicBoolean can be the best approach. This provides slightly different guarantees to volatile.

See question Java: volatile boolean vs AtomicBoolean question for more details.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
2

Taking a look at the classes in java/util/concurrent/atomic might be useful to you. Such as AtomicBoolean.

Paul Grime
  • 14,970
  • 4
  • 36
  • 58
0

Yes, making setters and getters synchronized is a good idea. To read or write a boolean is NOT atomic command , so in rare cases it may cause you some problems. ( you cannot be sure if you reading form RAM or cashe). Unless it is volatile.

Farseer
  • 4,036
  • 3
  • 42
  • 61
  • +1 for "To read or write a boolean is NOT atomic". But this is true even for volatile because simple assignments can lead to multiple JVM instructions and its this level at which synchronization has to be considered. – sgp15 Apr 01 '13 at 12:18
  • With the use of volatile, you do not need to synchronize your getter or setter. The semantics of volatile mean that you can get a guarantee when you read a variable marked as volatile that it's value is in a consistent state. – skipwalker Oct 09 '18 at 15:36