开发者

How to define static Arraylist in thread safe environment

开发者 https://www.devze.com 2023-03-07 14:32 出处:网络
How to define static Arraylist in thread safe env开发者_开发问答ironment. I have tried synchronized keyword but I heard using Automic classes from java concurrent package is a best solution for static

How to define static Arraylist in thread safe env开发者_开发问答ironment. I have tried synchronized keyword but I heard using Automic classes from java concurrent package is a best solution for static arraylist. Can anybody tell how to declare and use the static arraylist in safe manner?

Update:

in my code i have an static list to maintain the details of your those logging in the application

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

during login and accessing homepage(all time home page got accessed) checking for userdetails in userSessionList , if not availble adding the details in userSessionList and during logout removing the userdetails from the list. during login

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

during logout

  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;
}

so there is a chance to read and write request takes place in same time


It depends a lot on how you are going to use it. There are several options:

  • use CopyOnWriteArrayList - this is a modern concurrent implementation, best suited when there is relatively few writes and lots of reads
  • use a synchronized wrapper obtained via Collections.synchronizedList - it allows you to access the "original" unsynchronized list from e.g. within the containing object, but provide a thread safe access to the "outside world".

Vector is an old, obsolete collection implementation, which should not be used in new code.


The java.util.concurrent.CopyOnWriteArrayList is "a thread-safe variant of ArrayList in which all mutative operations add, set, and so on are implemented by making a fresh copy of the underlying array".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号