【问题标题】:How to define static Arraylist in thread safe environment如何在线程安全环境中定义静态 Arraylist
【发布时间】:2011-05-23 10:54:06
【问题描述】:

如何在线程安全环境中定义静态 Arraylist。我尝试过同步关键字,但听说使用 java concurrent 包中的 Automic 类是静态数组列表的最佳解决方案。谁能告诉我如何以安全的方式声明和使用静态数组列表?

更新:

在我的代码中,我有一个静态列表来维护您登录应用程序的详细信息

private static List<UserSessionForm> userSessionList = new ArrayList<UserSessionForm>();

在登录和访问主页期间(所有时间主页都被访问)检查 userSessionList 中的用户详细信息,如果不可用,则在 userSessionList 中添加详细信息,并在注销期间从列表中删除用户详细信息。 登录时

if (getUserSessionIndex(uform)!=-1) {
            this.getUserSession().add(usform);
            this.getSession().setAttribute("customerId", getCustomer_id());
        }

注销时

  public void logout(){
     int index = getUserSessionIndex(usform);
        //if user is  already loginned, remove that user from the usersession list
        if (index != -1) {
            UserAction.getUserSession().remove(index);
        }
   }

  private int getUserSessionIndex(UserSessionForm usform) {
    int index = -1;
    int tmp_index = 0;
    for (UserSessionForm tmp : UserAction.getUserSession()) {
        if (usform.equals(tmp)) {
            if (usform.getUserlogin_id() == tmp.getUserlogin_id()) {
                index = tmp_index;
                break;
            }
        }
        tmp_index += 1;
    }
    return index;
}

所以有机会同时发生读写请求

【问题讨论】:

  • 这取决于:ArrayList 会被同时访问吗?会不会同时写?它会是可变的吗?
  • 更新了我使用的实际编码

标签: java static thread-safety java.util.concurrent


【解决方案1】:

这在很大程度上取决于您将如何使用它。有几种选择:

  • 使用CopyOnWriteArrayList - 这是一种现代并发实现,最适合写入相对较少而读取较多的情况
  • 使用通过Collections.synchronizedList 获得的同步包装器 - 它允许您访问“原始”非同步列表,例如在包含对象内,但提供对“外部世界”的线程安全访问。

Vector 是一个旧的、过时的集合实现,不应在新代码中使用。

【讨论】:

    【解决方案2】:

    java.util.concurrent.CopyOnWriteArrayList 是“ArrayList 的线程安全变体,其中所有可变操作addset 等都是通过制作底层数组的新副本来实现的”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      相关资源
      最近更新 更多