Versions Compared

Key

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

...

Compound operations are operations that consist of more than one discrete operation. Expressions that include postfix or prefix increment (++), postfix or prefix decrement (--), or compound assignment operators always result in compound operations. Compound assignment expressions use operators such as *=, /=, %=, +=, -=, <<=, >>=, >>>=, ^= and |= [JLS 2005]. Compound operations on shared variables must be performed atomically to prevent data races and race conditions.

For information about the atomicity of a grouping of calls to independently atomic methods that belong to thread-safe classes, see rule VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic.

...

Execution of this code may result in a data race because the value of flag is read, negated, and written back.

...

This approach must not be used for getter methods that perform any additional operations other than returning the value of a volatile field without use of synchronization. Unless read performance is critical, this technique may lack significant advantages over synchronization [Goetz 2006].

Compliant Solution (Read-Write Lock)

...

Read-write locks allow shared state to be accessed by multiple readers or a single writer but never both. According to Goetz [Goetz 2006]

In practice, read-write locks can improve performance for frequently accessed read-mostly data structures on multiprocessor systems; under other conditions they perform slightly worse than exclusive locks due to their greater complexity.

...

MITRE CWE

CWE-667. Improper locking

 

CWE-413. Improper resource locking

 

CWE-366. Race condition within a thread

 

CWE-567. Unsynchronized access to shared data in a multithreaded context

Bibliography

[API 2006]

Class AtomicInteger

[Bloch 2008]

Item 66. Synchronize access to shared mutable data

[Goetz 2006]

2.3, Locking

[JLS 2005]

Chapter 17, Threads and Locks

 

§17.4.5, Happens-Before Order

 

§17.4.3, Programs and Program Order

 

§17.4.8, Executions and Causality Requirements

[Lea 2000]

Section 2.2.7, The Java Memory Model

 

Section 2.1.1.1, Objects and Locks

[Tutorials 2008]

Java Concurrency Tutorial

...