Iterating Through a Changing Collection with synchronized List - Java Thread

Java examples for Thread:CopyOnWriteArrayList

Description

Iterating Through a Changing Collection with synchronized List

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;/*from  ww  w  . ja  v a2s .com*/

  private void start() {
    final List<String> list = Collections
        .synchronizedList(new ArrayList<String>());
    startUpdatingThread(list);
    synchronized (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