简体   繁体   中英

How does the synchronized keyword work on an instance variable?

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.

  1. How does the synchronized key word have any effect in this case? Isnt a new lock created for each instance of the Client object?
  2. Would the usage of the synchronized keyword force the cache to be updated before a get/put operation is applied?
  3. Why would synchronization be necessary before a get? Is it to get the cache to be updated to the latest values assuming another thread applied a put interim.

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

  1. 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.

  2. 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.

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM