rspec/rules/S3042/java/rule.adoc
2023-07-14 12:41:50 +00:00

88 lines
2.4 KiB
Plaintext

== 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
[source,java,diff-id=1,diff-type=noncompliant]
----
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
[source,java,diff-id=1,diff-type=compliant]
----
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
* https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/Serializable.html[Java SE 17 & JDK 17 - Serializable Javadoc]
* https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html[The Java(TM) Tutorials - Synchronized Methods]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this "synchronized" keyword.
endif::env-github,rspecator-view[]