dir.by  
Поиск >>

Компьютер, программы
→
Java
→
Java (class, interface, collections, etc.)
 class CopyOnWriteArrayList<E> in Java 
посмотрели 1210 раз
обновлено: 6 October 2026
class CopyOnWriteArrayList<E> it is the same as ArrayList but safe in threads.

In CopyOnWriteArrayList all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created.
This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

CopyOnWriteArrayList
  implements interface List<E> this array, i.e. you can add and remove elements, get an element by index
  Java  
interface List<E> extends SequencedCollection<E>
{
Let's look at Functions >> ...
}
Examples
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.concurrent.CopyOnWriteArrayList ;

public class Program {
     public static void main(String[] args)
     {
          CopyOnWriteArrayList <String> myList1 = new CopyOnWriteArrayList <String>();

          // Add an element to the end
          myList1.add("Car");
          // myList1 = ["Car"]

          // Add an element to the end
          myList1.add("House");
          // myList1 = ["Car", "House"]

          // Add an element to the end
          myList1.add("Notebook");
          // myList1 = ["Car", "House", "Notebook"]

          // View item by index
          String elem = myList1.get(1);
          // elem = "House"
          // myList1 = ["Car", "House", "Notebook"]

          // Insert element by index 1
          myList1.add(1, "Airplane");
          // myList1 = ["Car", "Airplane", "House", "Notebook"]

          // Delete item by index
          myList1.remove(1);
          // myList1 = ["Car", "House", "Notebook"]
     }
}
  Kotlin     Creating a new Kotlin console application ... and write the code
import java.util.concurrent.CopyOnWriteArrayList;

fun main() {

     val myList1 = CopyOnWriteArrayList<String>()

     // добавляем элемент в конец
     myList1.add("Car")
     // myList1 = ["Car"]

     // добавляем элемент в конец
     myList1.add("House")
     // myList1 = ["Car", "House"]

     // добавляем элемент в конец
     myList1.add("Notebook")
     // myList1 = ["Car", "House", "Notebook"]

     // посмотреть элемент по индексу
     val elem = myList1[1]
     // elem = "House"
     // myList1 = ["Car", "House", "Notebook"]

     // вставить элемент по индексу 1
     myList1.add(1, "Airplane")
     // myList1 = ["Car", "Airplane", "House", "Notebook"]

     // удалить элемент по индексу
     myList1.removeAt(1)
     // myList1 = ["Car", "House", "Notebook"]
}
Documentation
  Java  
class CopyOnWriteArrayList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {

     final transient Object lock = new Object();

     private transient volatile Object[] array;

     final Object[] getArray() {
          return array;
     }

     final void setArray(Object[] a) {
          array = a;
     }

     public CopyOnWriteArrayList() {
          setArray(new Object[0]);
     }

     public CopyOnWriteArrayList(Collection<? extends E> c) {
          Object[] es;
          if (c.getClass() == CopyOnWriteArrayList.class)
               es = ((CopyOnWriteArrayList<?>)c).getArray();
          else {
               es = c.toArray();
               if (c.getClass() != java.util.ArrayList.class)
                    es = Arrays.copyOf(es, es.length, Object[].class);
          }
          setArray(es);
     }

     public CopyOnWriteArrayList(E[] toCopyIn) {
          setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
     }

     public int size() {
          return getArray().length;
     }

     public boolean isEmpty() {
          return size() == 0;
     }

     public boolean contains(Object o) {
          return indexOf(o) >= 0;
     }

     public int indexOf(Object o) {
          Object[] es = getArray();
          return indexOfRange(o, es, 0, es.length);
     }

     public int indexOf(E e, int index) {
          Object[] es = getArray();
          return indexOfRange(e, es, index, es.length);
     }

     public int lastIndexOf(Object o) {
          Object[] es = getArray();
          return lastIndexOfRange(o, es, 0, es.length);
     }

     public int lastIndexOf(E e, int index) {
          Object[] es = getArray();
          return lastIndexOfRange(e, es, 0, index + 1);
     }

     public Object clone() {
          try {
               @SuppressWarnings("unchecked")
               CopyOnWriteArrayList<E> clone =
                         (CopyOnWriteArrayList<E>) super.clone();
               clone.resetLock();
               // Unlike in readObject, here we cannot visibility-piggyback on the
               // volatile write in setArray().
               VarHandle.releaseFence();
               return clone;
          } catch (CloneNotSupportedException e) {
               // this shouldn't happen, since we are Cloneable
               throw new InternalError();
          }
     }

     public Object[] toArray() {
          return getArray().clone();
     }

     public <T> T[] toArray(T[] a) {
          Object[] es = getArray();
          int len = es.length;
          if (a.length < len)
               return (T[]) Arrays.copyOf(es, len, a.getClass());
          else {
               System.arraycopy(es, 0, a, 0, len);
               if (a.length > len)
                    a[len] = null;
               return a;
          }
     }

     public E get(int index) {
          return elementAt(getArray(), index);
     }

     public E getFirst() {
          Object[] es = getArray();
          if (es.length == 0)
               throw new NoSuchElementException();
          else
               return elementAt(es, 0);
     }

     public E getLast() {
          Object[] es = getArray();
          if (es.length == 0)
               throw new NoSuchElementException();
          else
               return elementAt(es, es.length - 1);
     }

     public E set(int index, E element) {
          synchronized (lock) {
               Object[] es = getArray();
               E oldValue = elementAt(es, index);

               if (oldValue != element) {
                    es = es.clone();
                    es[index] = element;
               }
               // Ensure volatile write semantics even when oldvalue == element
               setArray(es);
               return oldValue;
          }
     }

     public boolean add(E e) {
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               es = Arrays.copyOf(es, len + 1);
               es[len] = e;
               setArray(es);
               return true;
          }
     }

     public void add(int index, E element) {
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               if (index > len || index < 0)
                    throw new IndexOutOfBoundsException(outOfBounds(index, len));
               Object[] newElements;
               int numMoved = len - index;
               if (numMoved == 0)
                    newElements = Arrays.copyOf(es, len + 1);
               else {
                    newElements = new Object[len + 1];
                    System.arraycopy(es, 0, newElements, 0, index);
                    System.arraycopy(es, index, newElements, index + 1,
                              numMoved);
               }
               newElements[index] = element;
               setArray(newElements);
          }
     }

     public void addFirst(E e) {
          add(0, e);
     }

     public void addLast(E e) {
          synchronized (lock) {
               add(getArray().length, e);
          }
     }

     public E remove(int index) {
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               E oldValue = elementAt(es, index);
               int numMoved = len - index - 1;
               Object[] newElements;
               if (numMoved == 0)
                    newElements = Arrays.copyOf(es, len - 1);
               else {
                    newElements = new Object[len - 1];
                    System.arraycopy(es, 0, newElements, 0, index);
                    System.arraycopy(es, index + 1, newElements, index,
                              numMoved);
               }
               setArray(newElements);
               return oldValue;
          }
     }

     public E removeFirst() {
          synchronized (lock) {
               if (getArray().length == 0)
                    throw new NoSuchElementException();
               else
                    return remove(0);
          }
     }

     public E removeLast() {
          synchronized (lock) {
               int size = getArray().length;
               if (size == 0)
                    throw new NoSuchElementException();
               else
                    return remove(size - 1);
          }
     }

     public boolean remove(Object o) {
          Object[] snapshot = getArray();
          int index = indexOfRange(o, snapshot, 0, snapshot.length);
          return index >= 0 && remove(o, snapshot, index);
     }

     private boolean remove(Object o, Object[] snapshot, int index) {
          synchronized (lock) {
               Object[] current = getArray();
               int len = current.length;
               if (snapshot != current) findIndex: {
                    int prefix = Math.min(index, len);
                    for (int i = 0; i < prefix; i++) {
                         if (current[i] != snapshot[i]
                                   && Objects.equals(o, current[i])) {
                              index = i;
                              break findIndex;
                         }
                    }
                    if (index >= len)
                         return false;
                    if (current[index] == o)
                         break findIndex;
                    index = indexOfRange(o, current, index, len);
                    if (index < 0)
                         return false;
               }
               Object[] newElements = new Object[len - 1];
               System.arraycopy(current, 0, newElements, 0, index);
               System.arraycopy(current, index + 1,
                         newElements, index,
                         len - index - 1);
               setArray(newElements);
               return true;
          }
     }

     void removeRange(int fromIndex, int toIndex) {
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;

               if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
                    throw new IndexOutOfBoundsException();
               int newlen = len - (toIndex - fromIndex);
               int numMoved = len - toIndex;
               if (numMoved == 0)
                    setArray(Arrays.copyOf(es, newlen));
               else {
                    Object[] newElements = new Object[newlen];
                    System.arraycopy(es, 0, newElements, 0, fromIndex);
                    System.arraycopy(es, toIndex, newElements,
                              fromIndex, numMoved);
                    setArray(newElements);
               }
          }
     }

     public boolean addIfAbsent(E e) {
          Object[] snapshot = getArray();
          return indexOfRange(e, snapshot, 0, snapshot.length) < 0
                    && addIfAbsent(e, snapshot);
     }

     private boolean addIfAbsent(E e, Object[] snapshot) {
          synchronized (lock) {
               Object[] current = getArray();
               int len = current.length;
               if (snapshot != current) {
                    // Optimize for lost race to another addXXX operation
                    int common = Math.min(snapshot.length, len);
                    for (int i = 0; i < common; i++)
                         if (current[i] != snapshot[i]
                                   && Objects.equals(e, current[i]))
                              return false;
                    if (indexOfRange(e, current, common, len) >= 0)
                         return false;
               }
               Object[] newElements = Arrays.copyOf(current, len + 1);
               newElements[len] = e;
               setArray(newElements);
               return true;
          }
     }

     public boolean containsAll(Collection<?> c) {
          Object[] es = getArray();
          int len = es.length;
          for (Object e : c) {
               if (indexOfRange(e, es, 0, len) < 0)
                    return false;
          }
          return true;
     }

     public boolean removeAll(Collection<?> c) {
          Objects.requireNonNull(c);
          return bulkRemove(e -> c.contains(e));
     }

     public boolean retainAll(Collection<?> c) {
          Objects.requireNonNull(c);
          return bulkRemove(e -> !c.contains(e));
     }

     public int addAllAbsent(Collection<? extends E> c) {
          Object[] cs = c.toArray();
          if (c.getClass() != ArrayList.class) {
               cs = cs.clone();
          }
          if (cs.length == 0)
               return 0;
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               int added = 0;
               // uniquify and compact elements in cs
               for (int i = 0; i < cs.length; ++i) {
                    Object e = cs[i];
                    if (indexOfRange(e, es, 0, len) < 0 &&
                              indexOfRange(e, cs, 0, added) < 0)
                         cs[added++] = e;
               }
               if (added > 0) {
                    Object[] newElements = Arrays.copyOf(es, len + added);
                    System.arraycopy(cs, 0, newElements, len, added);
                    setArray(newElements);
               }
               return added;
          }
     }

     public void clear() {
          synchronized (lock) {
               setArray(new Object[0]);
          }
     }

     public boolean addAll(Collection<? extends E> c) {
          Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
                    ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
          if (cs.length == 0)
               return false;
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               Object[] newElements;
               if (len == 0 && (c.getClass() == CopyOnWriteArrayList.class ||
                         c.getClass() == ArrayList.class)) {
                    newElements = cs;
               } else {
                    newElements = Arrays.copyOf(es, len + cs.length);
                    System.arraycopy(cs, 0, newElements, len, cs.length);
               }
               setArray(newElements);
               return true;
          }
     }

     public boolean addAll(int index, Collection<? extends E> c) {
          Object[] cs = c.toArray();
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               if (index > len || index < 0)
                    throw new IndexOutOfBoundsException(outOfBounds(index, len));
               if (cs.length == 0)
                    return false;
               int numMoved = len - index;
               Object[] newElements;
               if (numMoved == 0)
                    newElements = Arrays.copyOf(es, len + cs.length);
               else {
                    newElements = new Object[len + cs.length];
                    System.arraycopy(es, 0, newElements, 0, index);
                    System.arraycopy(es, index,
                              newElements, index + cs.length,
                              numMoved);
               }
               System.arraycopy(cs, 0, newElements, index, cs.length);
               setArray(newElements);
               return true;
          }
     }

     public void forEach(Consumer<? super E> action) {
          Objects.requireNonNull(action);
          for (Object x : getArray()) {
               @SuppressWarnings("unchecked") E e = (E) x;
               action.accept(e);
          }
     }

     public boolean removeIf(Predicate<? super E> filter) {
          Objects.requireNonNull(filter);
          return bulkRemove(filter);
     }

     private boolean bulkRemove(Predicate<? super E> filter) {
          synchronized (lock) {
               return bulkRemove(filter, 0, getArray().length);
          }
     }

     boolean bulkRemove(Predicate<? super E> filter, int i, int end) {
          // assert Thread.holdsLock(lock);
          final Object[] es = getArray();
          // Optimize for initial run of survivors
          for (; i < end && !filter.test(elementAt(es, i)); i++)
               ;
          if (i < end) {
               final int beg = i;
               final long[] deathRow = nBits(end - beg);
               int deleted = 1;
               deathRow[0] = 1L; // set bit 0
               for (i = beg + 1; i < end; i++)
                    if (filter.test(elementAt(es, i))) {
                         setBit(deathRow, i - beg);
                         deleted++;
                    }
               // Did filter reentrantly modify the list?
               if (es != getArray())
                    throw new ConcurrentModificationException();
               final Object[] newElts = Arrays.copyOf(es, es.length - deleted);
               int w = beg;
               for (i = beg; i < end; i++)
                    if (isClear(deathRow, i - beg))
                         newElts[w++] = es[i];
               System.arraycopy(es, i, newElts, w, es.length - i);
               setArray(newElts);
               return true;
          } else {
               if (es != getArray())
                    throw new ConcurrentModificationException();
               return false;
          }
     }

     public void replaceAll(UnaryOperator<E> operator) {
          synchronized (lock) {
               replaceAllRange(operator, 0, getArray().length);
          }
     }

     void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
          // assert Thread.holdsLock(lock);
          Objects.requireNonNull(operator);
          final Object[] es = getArray().clone();
          for (; i < end; i++)
               es[i] = operator.apply(elementAt(es, i));
          setArray(es);
     }

     public void sort(Comparator<? super E> c) {
          synchronized (lock) {
               sortRange(c, 0, getArray().length);
          }
     }

     @SuppressWarnings("unchecked")
     void sortRange(Comparator<? super E> c, int i, int end) {
          // assert Thread.holdsLock(lock);
          final Object[] es = getArray().clone();
          Arrays.sort(es, i, end, (Comparator<Object>)c);
          setArray(es);
     }

     private void writeObject(java.io.ObjectOutputStream s)
          throws java.io.IOException {

          s.defaultWriteObject();

          Object[] es = getArray();
          // Write out array length
          s.writeInt(es.length);

          // Write out all elements in the proper order.
          for (Object element : es)
               s.writeObject(element);
     }

     private void readObject(java.io.ObjectInputStream s)
          throws java.io.IOException, ClassNotFoundException {

          s.defaultReadObject();

          // bind to new lock
          resetLock();

          // Read in array length and allocate array
          int len = s.readInt();
          SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, len);
          Object[] es = new Object[len];

          // Read in all elements in the proper order.
          for (int i = 0; i < len; i++)
               es[i] = s.readObject();
          setArray(es);
     }

     public String toString() {
          return Arrays.toString(getArray());
     }

     public boolean equals(Object o) {
          if (o == this)
               return true;
          if (!(o instanceof List))
               return false;

          List<?> list = (List<?>)o;
          Iterator<?> it = list.iterator();
          for (Object element : getArray())
               if (!it.hasNext() || !Objects.equals(element, it.next()))
                    return false;
          return !it.hasNext();
     }

     private static int hashCodeOfRange(Object[] es, int from, int to) {
          int hashCode = 1;
          for (int i = from; i < to; i++) {
               Object x = es[i];
               hashCode = 31 * hashCode + (x == null ? 0 : x.hashCode());
          }
          return hashCode;
     }

     public int hashCode() {
          Object[] es = getArray();
          return hashCodeOfRange(es, 0, es.length);
     }

     public Iterator<E> iterator() {
          return new COWIterator<E>(getArray(), 0);
     }

     public ListIterator<E> listIterator() {
          return new COWIterator<E>(getArray(), 0);
     }

     public ListIterator<E> listIterator(int index) {
          Object[] es = getArray();
          int len = es.length;
          if (index < 0 || index > len)
               throw new IndexOutOfBoundsException(outOfBounds(index, len));

          return new COWIterator<E>(es, index);
     }

     public Spliterator<E> spliterator() {
          return Spliterators.spliterator
                    (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
     }

     public List<E> subList(int fromIndex, int toIndex) {
          synchronized (lock) {
               Object[] es = getArray();
               int len = es.length;
               int size = toIndex - fromIndex;
               if (fromIndex < 0 || toIndex > len || size < 0)
                    throw new IndexOutOfBoundsException();
               return new COWSubList(es, fromIndex, size);
          }
     }

     public List<E> reversed() {
          return new Reversed<>(this, lock);
     }
}
Learn more about methods in the Java documentation: https://docs.oracle.com ...
 
← Previous topic
class Stack<E> in Java
 
Next topic →
interface Queue<E> in Java
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
Download and install
• Installation JDK (download and install the Java library for Windows)
• Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
• Error "JDK is missing" | Java
Java (class, interface, collections, etc.)
• Create a simple console app in IntelliJ IDEA to learn Java
• Access modifiers (private, protected, public) for a class and for methods and fields. | Java
• Collections in Java
• interface List<E> in Java
• class ArrayList<E> in Java
• class Vector<E> in Java
• class Stack<E> in Java
• class CopyOnWriteArrayList<E> in Java
• interface Queue<E> in Java
• interface Deque<E> in Java
• class LinkedList<E> in Java
• interface Set in Java
• class HashSet<E> in Java
• class LinkedHashSet<E> in Java
• interface Map in Java
• class HashMap<K,V> in Java
• class LinkedHashMap<K,V> in Java
• Collections.singletonList("Hello") returns an immutable list containing exactly one specified element | Java collection
• class Collections (all functions, algorithms) | Java
• stream.filter(...) select elements according to your criterion | Java collection | Example: allCars.stream().filter(item -> item.Price < 30000).toList()
• What is interface in Java ?
• You can add static functions to the interface | Java
• In the interface, using default, we create an implementation of the | this appeared in Java 8
• Directly in the code (at runtime) we make an implementation for the interface | Java
• Threads in Java
• lambda is an unnamed method (no name and no class owned) | Java
• Exceptions and handling in Java. Example: try {...} catch (Exception e) {...}
• Why use throws Exception in the function name in Java? Answer: The method throws an exception and there is no handling of try catch. Example: float CalculateDensity(float mass, float volume) throws Exception { ... throw new Exception("Error! Volume is zero."); ... }
Java web application (servlet, jsp page, basic functionality and no frameworks)
• Creating a new simple web application (jsp web page) | Java, Maven
• Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
• Installation Tomcat web server (download and install for Windows)
• Check, test Tomcat web server (create a new my.hml file)
• What is Maven
• What is a dynamic web page jsp (Java Server Page) ?
• How to install Smart Tomcat plugin in Intellij Idea
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
• What is Spring? Why use Spring in Java?
• What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
• What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
• Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
• Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
• Create Azure Web App with the type Java (free). That is, create an empty web server
• Put the Java Spring web application in Azure
• Connect to the application Azure Web App (Java) via FTP | use File Explorer
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
• How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
• What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
• Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
• What is Struts | Java
Courses, training
• Course "Java developer" from Yandex
Interview
• Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by