Why the fields of ConditionObject are not decorated as volatile?
ConditionObject has two fields firstWaiter and lastWaiter, both are not volatile.
I known ConditionObject can only be modified by thread which hold the exclusive lock, but what if one thread modified these two fields and late another thread read them, and did not read the recently updated value due to the cpu cache?
So why fields firstWaiter and lastWaiter can keep memory consistant without volatile?
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** These two fields are not volatile, may be modified by different thread */
private transient ConditionNode firstWaiter;
private transient ConditionNode lastWaiter;
}
A thread must own the
Lockwhich created theConditionbefore it can invoke the latter's methods. If the thread does not own the lock then an exception is thrown. If you look at the rest of the implementation, you will see the values of those two fields are never used, and the two fields are never written to, unlessisHeldExclusively()returns true. That method will only return true if the thread has acquired the lock, and acquiring a lock creates a happens-before relationship.In other words, those two fields are properly guarded by the
Lockand thus do not need to be volatile. It is no different from guarding your own state with a lock.