Re: Thread safety and atomic assignment (again)
On Apr 30, 2:38 pm, Philipp <sicsic...@freesurf.ch> wrote:
...
The question: Are the following code snippets thread safe and why? (my
opinion is on top, please correct if wrong):
What is your definition of thread safeness in the case of your
examples?
// Not thread safe. "value" needs to be volatile, else another thread
// might see a stale value
public final class Test1 {
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
This construction is regarded not to be thread safe. However, with
volatile int, you only solve the so-called visibility problem but I
would not regard the whole class thread safe even with the volatile
int. Here the question again what do you regard to be a stale value.
// Not thread safe. Because assignment to long is not atomic (although
// volatile).
public final class Test2 {
private volatile long value = 0;
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
}
Atomicity and volatileness are two different issues: "Locking can
guarantee both visibility and atomicity; volatile variables can only
guarantee visibility." (Java Concurrency in Practice, By Brian Goetz,
Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea)
As far as I know, however, single read or single write is atomic in
case of volatile long, so it should be thread safe in your
interpretation of thread safeness.
I think the rest of the examples, Test3-5 are all unsafe because of
the same reason: Atomicity and volatileness are two different issues.
In those cases you require atomicity to make it thread safe.
Best Regards,
Szabolcs