...
Consequently, a String
constant behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if every instance of an object maintains its own field lock
, the field points to a common String
constant in the JVM. Trusted code that locks on the same String
constant renders all synchronization attempts inadequate. Likewise, hostile code from any other package can exploit this vulnerability.
Compliant Solution (private internal raw Object
)
This compliant solution uses an internal private lock object. This is one of the few cases where a raw Object
is useful.
Code Block | ||
---|---|---|
| ||
private final Object lock = new Object();
synchronized(lock) {
// ...
}
|
Noncompliant Code Example (getClass()
lock object)
...