Static Field Write from Instance Method
ID |
java.static_from_instance |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:366, concurrency, reliability |
Description
Reports assignments in instance (non-static) methods that write to a static field. Writing to shared static state from an instance method is a common source of concurrency bugs.
Rationale
Static fields are shared across all instances of a class. When an instance method writes to a static field, multiple threads invoking the method on different instances can race on the same field without synchronization.
public class Counter {
private static int count = 0;
// Bad -- instance method modifies static state
public void increment() {
count++;
}
}
Remediation
Use a synchronized block, an AtomicInteger, or move the method to a static context with proper synchronization.
public class Counter {
private static final AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
}