Synchronized Block In Loop
ID |
java.loop_sync_in_loop |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
concurrency, efficiency |
Rationale
Acquiring and releasing a monitor lock on every iteration of a loop incurs significant overhead due to context switching and memory barriers. If the entire loop operates on shared state, it is more efficient to synchronize around the loop rather than inside it.
// Bad - lock acquired/released every iteration
for (String item : items) {
synchronized (lock) {
sharedList.add(item);
}
}
Remediation
Move the synchronized block outside the loop to acquire the lock once for all iterations.
// Good - single lock acquisition
synchronized (lock) {
for (String item : items) {
sharedList.add(item);
}
}