ConcurrentModificationException and ArrayList Performance

🛑 #Stop blindly using ArrayList<T>() and understand why ConcurrentModificationException is your friend. As Java developers, we use the Collection Framework daily. But we rarely stop to consider how it actually works under the hood—and that affects performance. Choosing the right structure—like ArrayList versus LinkedList—impacts your application’s speed and memory usage. This diagram visualizes how Java manages that data internally. Let’s break it down using real code: 1. ArrayList and the Cost of Dynamic Resizing ArrayList is excellent for random access, but it has to manage an underlying array. When it reaches capacity, Java must create a new, larger array and copy all the data over—an O(n) operation. The diagram shows: ArrayList -> Check Capacity -> Dynamic Resize -> MEMORY (Heap) How it looks in Java: import java.util.ArrayList; import java.lang.reflect.Field; public class ArrayListResizingDemo { public static void main(String[] args) throws Exception { // We initialize with a specific size. ArrayList<String> list = new ArrayList<>(5); System.out.println("1. New ArrayList created with capacity 5."); checkInternalCapacity(list); // Fill it up. The internal array size (5) matches the element count (5). System.out.println("\n2. Filling up capacity..."); for (int i = 0; i < 5; i++) { list.add("Element " + (i + 1)); } checkInternalCapacity(list); // The next addition triggers "Dynamic Resize." System.out.println("\n3. Adding the 6th element (triggers dynamic resize)..."); list.add("Element 6"); // The underlying array has now grown (~50%). checkInternalCapacity(list); } /** Helper function (uses Reflection, not for production!). */ private static void checkInternalCapacity(ArrayList<?> list) throws Exception { Field dataField = ArrayList.class.getDeclaredField("elementData"); dataField.setAccessible(true); Object[] internalArray = (Object[]) dataField.get(list); System.out.println(" --> Current internal array size: " + internalArray.length); System.out.println(" --> Number of actual elements stored: " + list.size()); } } #java #springboot

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories