60 lines
1.2 KiB
Plaintext
60 lines
1.2 KiB
Plaintext
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
|
|
|
|
[source,java]
|
|
----
|
|
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
|
|
|
|
[source,java]
|
|
----
|
|
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)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|