Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3475

Primitives should be "volatile"

    XMLWordPrintable

    Details

    • Message:
      Mark this "xxx" "volatile" or use an "AtomicXxx" instead.
    • Highlighting:
      Hide

      long|double xxx

      Show
      long|double xxx
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Targeted languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • CERT:
      VNA00-J., VNA05-J.

      Description

      Primitives can be read and written to atomically. Except for long and double, that is. These 64-bit primitives must be marked volatile in multi-threaded environments, or swapped out for their atomic counterparts: AtomicLong, and AtomicDouble to guarantee that their updates are always visible to other threads.

      Similarly, to ensure that updates to 32-bit primitives are visible to all threads, they should also be marked volatile.

      Noncompliant Code Example

      long m = 0;  // Noncompliant
      
      public void increment() {
        m++;
      }
      

      Compliant Solution

      volatile long m = 0;
      
      public void increment() {
        m++;
      }
      

      or

      AtomicLong m = new AtomicLong(0);
      
      public void increment() {
        m.incrementAndGet();
      }
      

      See

      • CERT, VNA00-J. - Ensure visibility when accessing shared primitive variables
      • CERT, VNA05-J. - Ensure atomicity when reading and writing 64-bit values

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: