0

I have thread class that has two variables var1 and var2 that might be accessed from different threads. Can we assume that using var2 via synchronized getter and setter is the same like using volatile var1 without them?

public class Processor extends Thread
{
    public volatile  boolean var1 = false
    private boolean var2 = false

    synchronized boolean getVar2 ()
    {
        return var2;
    }

    synchronized boolean setVar2 (boolean value)
    {
        return var2=value;
    }


    public void run()
    {
        ...
    }
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
vico
  • 17,051
  • 45
  • 159
  • 315
  • Just setting a variable to be volatile isn't a substitute for synchronisation if that's what you're asking? – imrichardcole Oct 18 '16 at 11:55
  • What is the idea behind the body of that setter? `return var2 = value;` That's abnormal, so need to know what you're trying to achieve there. – weston Oct 18 '16 at 11:59
  • Also var1 is a non-final public boolean, not sure if the above is real code or just to demonstrate an example, but it's probably bad news... – imrichardcole Oct 18 '16 at 12:02
  • In this example, there is no difference. In other examples, there is a big difference. You need to read the Oracle Tutorial on Concurrency (specifically, https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html) to understand the difference between synchronization and atomic operations. – Stephen C Oct 18 '16 at 12:11

2 Answers2

3

In this case yes. Because neither synchronized block both reads and writes the value.

Suppose we wanted to react to a value change, that would require both a read of the current value and a write of the new. For this, volatile would not be suitable:

synchronized void setVar(boolean value) {
  if (var != value) {
    var = value;
    someOnChangeMethod();
  }
}
weston
  • 54,145
  • 21
  • 145
  • 203
1

Yes, the two are equivalent wrt memory visibility. You lose automicity that synchronized offers if you have to do some check-then-set.

John Vint
  • 39,695
  • 7
  • 78
  • 108