rspec/rules/S2886/java/rule.adoc

69 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When one part of a getter/setter pair is ``++synchronized++`` the other part should be too. Failure to synchronize both sides of a pair may result in inconsistent behavior at runtime as callers access an inconsistent method state.
This rule raises an issue when either the method or the contents of one method in a getter/setter pair are synchrnoized but the other is not.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
public class Person {
String name;
int age;
public synchronized void setName(String name) {
this.name = name;
}
public String getName() { // Noncompliant
return this.name;
}
public void setAge(int age) { // Noncompliant
this.age = age;
}
public int getAge() {
synchronized (this) {
return this.age;
}
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
public class Person {
String name;
int age;
public synchronized void setName(String name) {
this.name = name;
}
public synchronized String getName() {
return this.name;
}
public void setAge(int age) {
synchronized (this) {
this.age = age;
}
}
public int getAge() {
synchronized (this) {
return this.age;
}
}
}
----
2021-04-28 16:49:39 +02:00
== See
* https://wiki.sei.cmu.edu/confluence/x/4jdGBQ[CERT, VNA01-J.] - Ensure visibility of shared references to immutable objects