Regarding the question in the 1st topic: (
https://shipilev.net/jvm-anatomy-park/1-lock-coarsening-for-...)
"
for (...) {
synchronized (obj) {
// something
}
}
…could it optimize into this?
synchronized (this) {
for (...) { The answer would be no in general, I think, since it is unsafe.
Moving the entire loop into the synchronized block would make the statement marked XXX above, i.e. "for (...)" execute inside the synchronized block, which has the potential to change the semantics (for example, the statement may include an rpc, and we don't want to make that rpc under the lock).
The earlier optimization of
synchronized (this) {
statement1;
}
synchronized (this) {
statement2;
}
to
synchronized (this) {
statement1;
statement2;
}
is safe.