如何在线程安全环境中定义静态数组。我尝试过同步关键字,但我听说使用java并发包中的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;
}因此,有机会在同一时间进行读写请求。
发布于 2011-05-23 11:01:22
这在很大程度上取决于你将如何使用它。有几种选择:
CopyOnWriteArrayList --这是一种现代的并发实现,最适合在写操作相对较少的情况下使用通过Collections.synchronizedList获得的同步包装器读取Vector是一个旧的、过时的集合实现,不应该在新代码中使用。
发布于 2011-05-23 10:59:04
java.util.concurrent.CopyOnWriteArrayList是“ArrayList的一个线程安全变体,其中所有的可变操作( add、set等)都是通过创建基础数组的新副本来实现的”。
https://stackoverflow.com/questions/6096237
复制相似问题