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

"writeObject" should not be the only "synchronized" code in a class

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this "synchronized" keyword.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • Analysis Scope:
      Main Sources, Test Sources
    • Implementation details:
    • FindBugs:
      WS_WRITEOBJECT_SYNC

      Description

      The purpose of synchronization is to ensure that only one thread executes a given block of code at a time. There's no real problem with marking writeObject synchronized, but it's highly suspicious if this serialization-related method is the only synchronized code in a class.

      Noncompliant Code Example

      public class RubberBall {
      
        private Color color;
        private int diameter;
      
        public RubberBall(Color color, int diameter) {  
          // ...
        }
      
        public void bounce(float angle, float velocity) { 
          // ... 
        }
      
        private synchronized void writeObject(ObjectOutputStream stream) throws IOException { // Noncompliant
          // ...
        }
      }
      

      Compliant Solution

      public class RubberBall {
      
        private Color color;
        private int diameter;
      
         public RubberBall(Color color, int diameter) {  
          // ...
        }
      
        public void bounce(float angle, float velocity) { 
          // ... 
        }
      
        private void writeObject(ObjectOutputStream stream) throws IOException {
          // ...
        }
      }
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated: