All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S3042.html Maven / Gradle / Ivy

Why is this an issue?

Synchronization is a mechanism used when multithreading in Java to ensure that only one thread executes a given block of code at a time. This is done to avoid bugs that can occur when multiple threads share a given state and try to manipulate simultaneously.

Object serialization is not thread-safe by default. In a multithreaded environment, one option is to mark writeObject with synchronized to improve thread safety. It is highly suspicious, however, if writeObject is the only synchronized method in a class. It may indicate that serialization is not required, as multithreading is not used. Alternatively, it could also suggest that other methods in the same class have been forgotten to be made thread-safe.

How to fix it

Consider whether this class is used in a multithreaded context. If it is, ask yourself whether other methods in this class should also be marked as synchronized. Otherwise, remove the synchronized modifier from this method.

Code examples

Noncompliant code example

public class RubberBall implements Serializable {

  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, "writeObject" is the only synchronized method in this class
    // ...
  }
}

Compliant solution

public class RubberBall implements Serializable {

  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 { // Compliant, no methods in this class are synchronized
    // ...
  }
}

Resources





© 2015 - 2025 Weber Informatics LLC | Privacy Policy