Re: Can you use "synchronized" for data members
On 11/9/2011 2:02 PM, Tom Anderson wrote:
On Wed, 9 Nov 2011, markspace wrote:
On 11/9/2011 10:32 AM, Nagrik wrote:
Can the "synchronized" kew word be used in front of data members.
No. Use "volatile" for that.
Yes. Although it isn't *quite* the same thing.
By which i mean that:
class Smeagol {
private volatile int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
And:
class Deagol {
private int x;
public synchronized int getX() {
return x;
}
public synchronized void setX(int x) {
this.x = x;
}
}
Have slightly different semantics. If thread A calls getX, and then
thread B calls setX, then with Deagol, there is a happens-before
relationship between the two calls. With Smeagol, there is not. Whereas
if A calls setX and then B calls getX, both Smeagol and Deagol will
generate a happens-before relationship.
Or so i believe. I hope someone will correct me if i'm wrong.
The good news is that in most cases, the weaker guarantees provided by
Smeagol's volatile are actually just what you want (because you don't
care that a write to a variable happens after a read), and the JVM can
generate a more streamlined sequence of instructions for it.
Very often, for int, you need a much stronger guarantee. Consider
"x++;". It involves two memory accesses, one to read the old value of x
and the other to write the new value. If two or more threads are doing
similar operations at the same time, something has to be done to prevent
the following sort of thing:
x is initially 0
Thread A reads x, getting 0.
Thread B reads x, getting 0.
Thread A writes 1 to x.
Thread B writes 1 to x.
Two threads have each executed x++, but x has only increased in value by 1.
In many cases, AtomicInteger is a better choice than int for a variable
that needs to be operated on by multiple threads.
Patricia