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++``.
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
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
// ...
}
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Compliant Solution
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 {
// ...
}
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]