Created
June 18, 2018 11:18
-
-
Save erikhuizinga/84f8726d68c993990f28e20ad9f96007 to your computer and use it in GitHub Desktop.
Demo of CopyOnWriteArrayList behaviour: while iterating through a previously nonempty list, clearing the list does not influence the iteration: all elements that existed when the iterator was created exist, despite the list being cleared while iterating.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import com.google.common.collect.Lists; | |
import java.util.List; | |
import java.util.concurrent.atomic.AtomicBoolean; | |
public class CopyOnWriteArrayListBehaviour { | |
// Change this to a regular ArrayList to see what different behaviour the CopyOnWriteArrayList has | |
private static final List<Integer> list = Lists.newCopyOnWriteArrayList(); | |
// private static final List<Integer> list = new ArrayList<>(); | |
public static void main(String[] args) { | |
list.add(1); | |
list.add(2); | |
list.add(3); | |
// Use AtomicBoolean for effectively final object access from multiple threads | |
final AtomicBoolean isInIteratorLoop = new AtomicBoolean(false); | |
final int theWait = 250; // milliseconds | |
// Start a new thread for concurrent behaviour | |
new Thread( | |
() -> { | |
for (Integer integer : list) { | |
System.out.println("In iterator loop, list = " + list); | |
isInIteratorLoop.set(true); | |
try { | |
while (!list.isEmpty()) { | |
System.out.println("In iterator loop, waiting for list cleared"); | |
Thread.sleep(theWait); | |
} | |
System.out.println(integer); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
System.out.println("In iterator loop, finished loop"); | |
isInIteratorLoop.set(false); | |
}) | |
.start(); | |
try { | |
while (!isInIteratorLoop.get()) { | |
System.out.println("In main thread, waiting for iterator loop"); | |
Thread.sleep(theWait); | |
} | |
list.clear(); | |
System.out.println("In main thread, list cleared"); | |
while (isInIteratorLoop.get()) { | |
System.out.println("In main thread, waiting for iterator loop to finish"); | |
Thread.sleep(theWait); | |
} | |
System.out.println("In main thread, list = " + list); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment