I'm looking at some legacy code that's of the form
public class Client {
private final Cache cache;
.....
Client( final Cache cache) {
this.cache = cache;
}
public Value get(Key key) {
synchronized(cache){
return this.cache.get(key);
}
}
public void put(Key k , Value v) {
synchronized(this.cache){
return cache.put(k, v);
}
}
}
}
I've never seen an instance variable that could be modified being used as a lock Object, since typically locks are usually final Object instances or just direct Locks via the Java API.
Client
object? synchronized
keyword force the cache to be updated before a get/put operation is applied? synchronized
provides the same guarantees irrespective of whether it is used on a static variable or an instance variable. ie, memory visibility and atomicity. In your case, it provides thread safety at instance level for the attribute cache
.
So, coming to your questions
You are right. Each instance of Client
will have its own lock. But this is useful when an instance of Client
is shared between multiple clients.
After the execution of the synchronized
block, CPU local caches will be flushed into the main memory and this ensures memory visibility for other threads. At the start of execution of the synchronized
block, local CPU caches will be invalidated and loaded from the main memory. So yes, synchronized
will cause the instance variable cache
to have the up to date values. Please see Synchronization for more details.
The reason is the same as 2. ie, to provide memory visibility.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.