Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Programs must not use instance locks to protect static shared data because instance locks are ineffective when two or more instances of the class are created. Consequently, failure to use a static lock object leaves the shared state unprotected against concurrent access. Lock objects for classes that can interact with untrusted code must also be private and final, as shown in LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code.

Noncompliant Code Example (Nonstatic Lock Object for Static Data)

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

Code Block
bgColor#FFcccc
public final
Wiki Markup
Static shared data should not be protected using instance locks because the instance locks are ineffective when two or more instances of the class are created. Consequently, the shared state is not safe for concurrent access.

h2. Noncompliant Code Example (non-static lock object for {{static}} data)

This noncompliant code example uses a non-static lock object to guard access to a {{static}} field {{counter}}. If two {{Runnable}} tasks, each consisting of a thread are started, they will create two instances of the lock object and lock on each separately. 

{mc} Do not declare the classes non-public and final, otherwise threads will be unable access counter {mc}

{code:bgColor=#FFcccc}
public 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 Runnable(int r1i = 0; i new< CountBoxes()2;
 i++) {
  Thread t1 = new Thread(r1);
    Runnable r2 = new CountBoxes();
    Thread t2 = new Thread(r2);
    t1.start();
    t2.start();}
  }
}
{code}

This does not prevent either thread from observing an inconsistent value of {{counter}} because the increment operation on {{volatile}} fields is not atomic in the absence of proper synchronization. 


h2. Noncompliant Code Example (method synchronization for {{static}} data)

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

{code:bgColor=#FFcccc}
public

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 VNA02-J. Ensure that compound operations on shared variables are atomic for more information).

Noncompliant Code Example (Method Synchronization for Static Data)

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

Code Block
bgColor#FFcccc
public final class CountBoxes implements Runnable {
  private static volatile int counter;
  // ...

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

The problem is that this lock is associated with each instance of the class and not with the class object itself. Consequently, threads constructed using different {{Runnable}} instances may observe inconsistent values of the {{counter}}.


h2. Compliant Solution ({{static}} lock object)

This compliant solution declares the lock object as {{static}} and consequently, ensures the atomicity of the increment operation.

{code

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.

Compliant Solution (Static Lock Object)

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

Code Block
bgColor#ccccff
:bgColor=#ccccff}
public class CountBoxes implements Runnable {
  private static int counter;
  // ...

  private static final Object lock = new Object();    
  
  public void run() {
    synchronized (lock) {
      counter++; 
      // ...
    }
  }
  // ...
}
{code}

There is no requirement of declaring the {{counter}} variable as {{volatile}} when synchronization is used.

h2. Risk Assessment

Using an instance lock to protect static shared data provides no synchronization properties and can lead to non-deterministic behavior.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON34- J | medium | probable | medium | {color:#cc9900}{*}P8{*}{color} | {color:#cc9900}{*}L2{*}{color} |



h3. Automated Detection

TODO

h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON34-J].

h2. References

\[[API 06|AA. Java References#API 06]\] 


----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|VOID CON00-J. Synchronize access to shared mutable variables]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON03-J. Do not use background threads during class initialization]

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

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

LCK06-J

Medium

Probable

Medium

P8

L2

Automated Detection

Some static analysis tools can detect violations of this rule.

ToolVersionCheckerDescription
Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.LCK06.INSTLOCKDo not use an instance lock to protect shared static data
SpotBugs

Include Page
SpotBugs_V
SpotBugs_V

SSD_DO_NOT_USE_INSTANCE_LOCK_ON_SHARED_STATIC_DATAImplemented since 4.6.0

Related Guidelines

MITRE CWE

CWE-667, Improper Locking

Bibliography

Issue Tracking

Tasklist
Review List
Review List
 
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name|| 
|T|M|F|1270215165305|1271447005294|rcs_mgr|"Ideally, the lock should also be private and final" => I have been penalized for using "ideally" before. I would just remove that sentence or make it more definitive. Note that we also have an NCE that uses method synchronization. Perhaps we also need a CS with a static method.| 


...

Image Added Image Added Image Added