...
In this noncompliant code example, if one thread repeatedly calls the assignValue()
method and another thread repeatedly calls the printLong()
method, the printLong()
method could occasionally print a value of i
that is neither zero nor the value of the j
argument.
Code Block | ||
---|---|---|
| ||
class LongContainer {
private long i = 0;
void assignValue(long j) {
i = j;
}
void printLong() {
System.out.println("i = " + i);
}
}
|
...
This compliant solution declares i
volatile. Writes and reads of long
and double
volatile values are always atomic.
Code Block | ||
---|---|---|
| ||
class LongContainer {
private volatile long i = 0;
void assignValue(long j) {
i = j;
}
void printLong() {
System.out.println("i = " + i);
}
}
|
...
Some static analysis tools are capable of detecting violations of this rule.
Tool | Version | Description | ||||||
---|---|---|---|---|---|---|---|---|
ThreadSafe |
| Implemented |
Related Guidelines
...
3.1.2, Non-atomic 64-Bit Operations | |
| |
[JLS 2005] | §17.7, Non-atomic Treatment of double and long |