3 ms·
> when they implement synchronization wrong. Yes, but there are lots of ways to implement synchronization wrong because you don't understand memory barriers.
by kbutler 9y ago
> when they implement synchronization wrong.
Yes, but there are lots of ways to implement synchronization wrong because you don't understand memory barriers.
For instance, Doug Lea's article linked above includes this very simple Java code, which breaks because it wasn't aware of memory barriers:
// Broken multithreaded version
// "Double-Checked Locking" idiom
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null)
helper = new Helper();
}
return helper;
}
// other functions and members...
}
[dfox: can't reply, guess we're nesting too deeply.
Per the above, the simple rule has to be modified to "do not touch OR READ shared state outside of relevant critical section". Easy to make errors...]
- dfox 9y agoThere is simple rule for that: do not touch shared state outside of relevant critical section. To some extent the cited problem is unique to Java, because the whole monitor concept just creates confusion about what synchronized really means (and also creates significant overhead by making literally everything usable as mutex). Pretty common misconception is that synchronized is akin to some kind of read-write lock (in which case the code above would work as expected).