Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: REM Cost Reform


 

********** Text below this note not yet converted from Java to C! ************

...

This noncompliant code example attempts to guard access to the static counter field using a non-static lock object. When two Runnable tasks are started, they create two instances of the lock object and lock on each instance separately.

...


public final class CountBoxes implements Runnable {
  private static volatile int counter;
  // ...
  private final Object lock = new Object();
 

  @Override public void run() {
    synchronized (lock) {
      counter++;
      // ...
    }
  }
 

  public static void main(String[] args) {
    for (int i = 0; i < 2; i++) {
    new Thread(new CountBoxes()).start();
    }
  }
}
 


This example fails to prevent either thread from observing an inconsistent value of counter because the increment operation on volatile fields fails to be atomic in the absence of proper synchronization. (See rule VNA02-J. Ensure that compound operations on shared variables are atomic for more information.)

...

This noncompliant code example uses method synchronization to protect access to a static class counter field.


 

public final class CountBoxes implements Runnable {
  private static volatile int counter;
  // ...
 

  public synchronized void run() {
    counter++;
    // ...
  }
  // ...
}
 


In this case, the method synchronization uses the intrinsic lock associated with each instance of the class rather than the intrinsic lock associated with the class itself. Consequently, threads constructed using different Runnable instances may observe inconsistent values of counter.

...

This compliant solution ensures the atomicity of the increment operation by locking on a static object.

...


public class CountBoxes implements Runnable {
  private static int counter;
  // ...
  private static final Object lock = new Object();
 

  public void run() {
    synchronized (lock) {
      counter++;
      // ...
    }
  }
  // ...
}
 


It is unnecessary to declare the counter variable volatile when using synchronization.

...

Using an instance lock to protect static shared data can result in nondeterministic behavior.

Rule

Severity

Likelihood

Detectable

Remediation Cost

Repairable

Priority

Level

LCK06

CON06-

J

C

Medium

Probable

Medium

No

No

P8

P4

L2

L3

Automated Detection

Some static analysis tools can detect violations of this rule.

Related Guidelines

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V

Supported, but no explicit checker

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CWE 2.11
MITRE CWE
CWE-667, Improper LockingPrior to 2018-01-12: CERT:

Bibliography

...


...

Image Modified Image Modified Image Modified