58 lines
1.6 KiB
Plaintext
58 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In a multi-threaded situation, un-``++synchronized++`` lazy initialization of static fields could mean that a second thread has access to a half-initialized object while the first thread is still creating it. Allowing such access could cause serious bugs. Instead. the initialization block should be ``++synchronized++``.
|
|
|
|
|
|
Similarly, updates of such fields should also be ``++synchronized++``.
|
|
|
|
|
|
This rule raises an issue whenever a lazy static initialization is done on a class with at least one ``++synchronized++`` method, indicating intended usage in multi-threaded applications.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
private static Properties fPreferences = null;
|
|
|
|
private static Properties getPreferences() {
|
|
if (fPreferences == null) {
|
|
fPreferences = new Properties(); // Noncompliant
|
|
fPreferences.put("loading", "true");
|
|
fPreferences.put("filterstack", "true");
|
|
readPreferences();
|
|
}
|
|
return fPreferences;
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
private static Properties fPreferences = null;
|
|
|
|
private static synchronized Properties getPreferences() {
|
|
if (fPreferences == null) {
|
|
fPreferences = new Properties();
|
|
fPreferences.put("loading", "true");
|
|
fPreferences.put("filterstack", "true");
|
|
readPreferences();
|
|
}
|
|
return fPreferences;
|
|
}
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|