rspec/rules/S3042/java/rule.adoc

65 lines
1.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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 {
// ...
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this "synchronized" keyword.
endif::env-github,rspecator-view[]