Iterating Through a Changing Collection with CopyOnWriteArrayList - Java Thread

Java examples for Thread:CopyOnWriteArrayList

Description

Iterating Through a Changing Collection with CopyOnWriteArrayList

Demo Code

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

public class Main {
  Random random = new Random();

  Thread updatingThread;/*ww  w  .ja  v a2s . c o m*/

  private void start() {
    copyOnWriteSolution();
  }

  private void copyOnWriteSolution() {
    CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
    startUpdatingThread(list);
    list.stream().forEach((element) -> {
      System.out.println("Element :" + element);
    });
    stopUpdatingThread();
  }
  private void stopUpdatingThread() {
    updatingThread.interrupt();
  }
  private void startUpdatingThread(final List<String> list) {
    updatingThread = new Thread(() -> {
      long counter = 0;
      while (!Thread.interrupted()) {
        int size = list.size();
        if (random.nextBoolean()) {
          if (size > 1) {
            list.remove(random.nextInt(size - 1));
          }
        } else {
          if (size < 20) {
            list.add("Random string " + counter);
          }
        }
        counter++;
      }
    });
    updatingThread.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    Main recipe = new Main();
    recipe.start();
  }
}

Result


Related Tutorials