A volatile field is updated with ++, -- or a compound assignment, which is not atomic
What it finds
count++ on a volatile field is a read followed by a write, and two threads can both read the old value: one increment is lost. volatile makes each read and write visible, not the pair atomic. An AtomicInteger or a lock makes the update atomic.
Reported are ++, -- and compound assignments such as += on volatile fields of this file, outside synchronized code.
From the rule's source, volatile_compound.rs.
class Stats { private volatile int hits; private volatile long bytes; private int plain; void record(int size) { hits++;tx0 reports: this update of the volatile field hits is not atomic this.bytes += size;tx0 reports: the volatile field bytes plain++; hits = 0; synchronized (this) { hits++; } }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:volatile-compound" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:volatile-compound] reason="..."tx0 explain tx0/java:volatile-compound shows the same in the terminal. Found a false positive? Report it.