java concurrent Array List access

前端 未结 2 1966
别跟我提以往
别跟我提以往 2020-12-10 19:18

I have an object which is a singleton. This object declares:

List players = new ArrayList();

The same object al

相关标签:
2条回答
  • 2020-12-10 19:55

    If you don't plan on updating it often use a CopyOnWriteArrayList otherwise @tieTYT's suggestion works.

    You can also manage this yourself by returning a copy of the list instead of the actual list within the getPlayers. (If you are using Collections.synchronizedList)

    public List<Player> getPlayers(){
        synchronized(list){
           Collections.unmodifiableList(new ArrayList<Player>(list));
        }
    }
    

    This has the side effect of a list being out of date after an add/remove is done

    Edit: Stealing Grzegorz suggestion for unmodifiableList

    0 讨论(0)
  • 2020-12-10 20:06

    The documentation answers your question.

    It is imperative that the user manually synchronize on the returned list when iterating over it:

    List list = Collections.synchronizedList(new ArrayList());
          ...
      synchronized(list) {
          Iterator i = list.iterator(); // Must be in synchronized block
          while (i.hasNext())
              foo(i.next());
      }
    

    As for contains and remove, you shouldn't have to synchronize manually. I'm looking at the source code of Collections and it looks like it does that for you:

        public boolean contains(Object o) {
            synchronized (mutex) {return c.contains(o);}
        }
        public boolean remove(Object o) {
            synchronized (mutex) {return c.remove(o);}
        }
    

    It wouldn't be a synchronized list if you have to do this stuff on your own.

    0 讨论(0)
提交回复
热议问题