ArrayList Sync

In ArrayListapi we have:

Please note that this implementation is not synchronized. If several threads access the ArrayList instance at the same time and at least one of the threads changes the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or removes one or more elements or explicitly changes the size of the support array; just setting the value of an element is not a structural modification.) This is usually done by synchronizing on some object, which naturally encapsulates the list. If such an object does not exist, the list must be "wrapped" using the Collections.synchronizedList Method list.

This is what is meant by "Usually this is achieved by synchronizing on some object that naturally encapsulates the list"? How does this relate to the exclusion of parallel modification?

+4
source share
3 answers

from ArrayList

This is usually done by synchronizing on some object, which naturally encapsulates the list. If such an object does not exist, the list must be "wrapped" using the Collections.synchronizedList method. This is best done at creation time to prevent accidental unsynchronized access to the list:

   List list = Collections.synchronizedList(new ArrayList(...));

" " , , , :

class ParkingLot{
   private ArrayList<Cars> spots;

   public boolean park(int spotNumber, Car car){          
       if( spots.get(spotNumber)==null){
            spot.set(spotNumber,car);
            return true;
       }
       return false;
   }
}

ParkinLot spot. park(), ParkingLot, .

ConcurrentModificationException , ( ), (.. , , ).

+8

Vector ? .

0

" - , , , "

, ArrayList, , ArrayList synchronized.

class MyClasss{

      private final ArrayList list;
      ......
      ......
      ......
 }

MyClass, , / , .

class MyClasss{

      private final ArrayList list;
      ......
      ......
      ......
      public void fun(){
          synchronized(this){
                list.add(....)
           }
 }

? , , ConcurrentModificationException JVM.

ConcurrentModificationException java, Collection. , , .

So, if you are synchronize Collection, then the simultaneous modification of the modification counter will not occur, as a result of which the value will not be selected ConcurrentModificationException.

Hope this helps.

0
source

All Articles