如何在线程安全环境中定义静态 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;
}
所以有机会同时发生读写请求