Yes. Synchronizing on lockObject establishes a Happens Before Relationship (aka sets up a memory barrier). This means that all threads that subsequently get the lock will see any changes that happened while the lock was held previously.
For what it's worth, though, your implementation of lazy initialization is flawed. This is the proper way:
private volatile String cachedToken;
retrieveToken() {
if (cachedToken == null) {
synchronized(lockObject) {
if (cachedToken == null) {
cachedToken = goGetNewToken();
}
}
}
return cachedToken
}
This way you only have to get the lock a small handful of times when Threads first start requesting it. After that the cachedToken will not be null, and you won't need to synchronize.
lockObject
after another thread writes then leaves, the entering thread will see the write. – TerefahlockObject
rather than using cachedToken. I can make that field final to make sure the reference never changes. – Balling