0

如何在线程安全环境中定义静态 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;
}

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

4

2 回答 2

4

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

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

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

于 2011-05-23T11:01:22.017 回答
3

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

于 2011-05-23T10:59:04.640 回答