有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java避免在线程处于特定块中时对静态对象进行全局修改

我有两个类,第一个类(ClassServletA.java)是HttpServlet,它在HashMap中存储IP地址和访问时间,我想每天备份数据库中的HashMap,所以我计划任务并将静态HashMap对象存储在DB中,然后重新初始化HashMap(在存储在DB中之后)

是否可以全局锁定静态对象

 public class ClassServletA {
  public static  Map<String,String> myMap = new HashMap<String, String>();

   void doGet(HttpServeltRequest request , HttpServletResponse response){
    myMap.put("ipaddress", "accessTime");
   }
}

第二类是调度程序:

public class MyDailyTask implements Job {
  void executeMethod(){
  //Writing the map object to file or database login here
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(ClassServletA.myMap);
    out.flush();
    out.close();
    // Reinitialize the hashmap 
    ClassServletA.myMap=new HashMap<String,String> ();
    }
}

是否可以锁定或避免修改ClassServletA。当调度器(MyDailyTask.java)执行executeMethod()时,在调度时间段内全局映射myMap对象


共 (1) 个答案

  1. # 1 楼答案

    如果您只是想确保在执行executeMethodmyMap没有被修改,但又不想阻止其他线程对它的访问,那么可以使用^{}

      public class ClassServletA {
      public static final AtomicReference<Map<String,String>> myMap = new AtomicReference(new HashMap<>());
    
       void doGet(HttpServeltRequest request , HttpServletResponse response){
        myMap.get().put("ipaddress", "accessTime");
       }
    }
    
    public class MyDailyTask implements Job {
      void executeMethod(){
      //Writing the map object to file or database login here
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(ClassServletA.myMap.getAndSet(new HashMap<>()));
        out.flush();
        out.close();
        }
    }
    

    如果您想阻止对^ {}的访问,请考虑使用ReadWriteLock。参见其他关于它的问题:Java Concurrency: ReadWriteLock on Variable

    无论哪种方式,HashMap都不是线程安全的,需要适当的同步才能进行并发访问。见Java Multithread Access Static Variable