Question

In the class ReentrantReadWriteLock is the following curious comment:

transient ThreadLocalHoldCounter readHolds;

Sync() {
    readHolds = new ThreadLocalHoldCounter();
    setState(getState()); // ensures visibility of readHolds
}

what does it mean by "ensures visibility"? The reason I ask is that I have a situation where it looks as though the thread local readHolds is being reset (thread locals are implemented as WeakReferences so that shouldn't happen as long as the containing Sync object is still alive). setState/getState simply alter another instance variable and don't touch readHolds.

Was it helpful?

Solution

The setState(int) method performs an assignment to a volatile variable. This causes any assignments performed by the current thread—including readHolds—to be flushed to "main memory".

Other threads calling getState() read this same volatile variable. Since the variable is volatile, the thread's cache is cleared first, forcing subsequent read operations to go out to main memory, where they will find the most recent value of readHolds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top