I have read that you should use volatile when a thread accesses a variable to make sure that the threads see the correct value, but does that also apply when the variable is used within a method?
Example code:
public class Limiter
{
int max = 0;
public synchronized void doSomething()
{
max++;
if(max < 10)
System.out.println("Work");
System.out.println(max);
}
}
Is it safe to assume that if a multiple thread calls doSomething, then max will be set to the same state as when the previous Thread called the method?
Because doSomething() is synchronized, I know that only a single thread can modify max, but what happens when the next thread calls it? Can max be a different value because it doesn’t use volatile? Or is it safe because the “Limiter” instance modifies it itself?
volatileis part of the declaration of a field, not part of its use. It would make no sense to declare a local variable as volatile, as local variables won’t be seen by different threads.In your case, you’re fine so long as no code in non-synchronized methods accesses
max– the memory model basically makes sure that so long as all code acquires/releases the same monitor “guarding” a variable, all threads will see a consistent sequence of values. (Aside from anything else, the fact that the threads each have to acquire the monitor before accessing the value means only one thread will be able to access the value at a time – you could write a total ordering of “thread X had the monitor at time t0-t1, thread Y had the monitor at time t4-t5” etc.)