The correct way to access read-only mapping synchronously in Java

I'm writing a simulation of the databaseconfiguration class, which reads the configuration from the database. I need some suggestions on synchronization

public class MyDBConfiguration{
   private Connection cn;
   private String table_name;
   private Map<String,String> key_values = new HashMap<String,String>();
   public MyDBConfiguration (Connection cn,String table_name) {
      this.cn = cn;
      this.table_name = table_name;
      reloadConfig();
   }
   public String getProperty(String key){
       return this.key_values.get(key);
   }
   public void reloadConfig() {
      Map<String,String> tmp_map = new HashMap<String,String> ();
      // read  data from database
      synchronized(this.key_values)
      {
          this.key_values = tmp_map;
      }
   }
}

So I have a few questions 1. Assuming that the property is read-only, do I use synchronization in getproperty? 2. Whether it is meaningful to perform this operation in reloadconfig key_ values = Collections. synchronizedMap(tmp_map)?

thank you.

Solution

>It is assumed that the key will not be put after reloadconfig_ Values, you will need to synchronize the read and write of the access map You only violate this rule by synchronizing assignments You can delete the synchronized block and set the key_ Values is specified as volatile to solve this problem

Note: in addition, you should never synchronize fields that are about to change The results are very difficult to predict

Editor: about other answers It is strongly recommended that all shared variable data must be synchronized because the effect is non deterministic key_ The values field is a shared variable field, and its assignment must be synchronized

Edit: and clear any confusion with Bruno Reis If you still fill TMP_ Map, and after filling, the volatile field will be legal and assigned to this key_ Values, it looks like:

private volatile Map<String,String>();

  ..rest of class 

   public void reloadConfig() {
      Map<String,String> ();
      // read  data from database

      this.key_values = tmp_map;
   }

You still need the same style, otherwise Bruno Reis points out that it won't be thread safe

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>