From b9484b244b683f54882bba6d59f82ed75867f801 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 30 Apr 2017 08:21:11 +0200 Subject: [PATCH] BAEL-881 copyOnWriteArrayList tests (#1750) --- .../copyonwrite/CopyOnWriteArrayListTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java new file mode 100644 index 0000000000..c71c193372 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java @@ -0,0 +1,53 @@ +package com.baeldung.concurrent.copyonwrite; + + +import org.junit.Test; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class CopyOnWriteArrayListTest { + + @Test + public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() { + //given + final CopyOnWriteArrayList numbers = + new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); + + //when + Iterator iterator = numbers.iterator(); + numbers.add(10); + + //then + List result = new LinkedList<>(); + iterator.forEachRemaining(result::add); + assertThat(result).containsOnly(1, 3, 5, 8); + + //and + Iterator iterator2 = numbers.iterator(); + List result2 = new LinkedList<>(); + iterator2.forEachRemaining(result2::add); + + //then + assertThat(result2).containsOnly(1, 3, 5, 8, 10); + + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() { + //given + final CopyOnWriteArrayList numbers = + new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); + + //when + Iterator iterator = numbers.iterator(); + while (iterator.hasNext()) { + iterator.remove(); + } + } +}