Pages

Wednesday, 1 March 2017

Chapter 30 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

30.9 (Demonstrate ConcurrentModificationException) The iterator is fail-
fast. Write a program to demonstrate it by creating two threads that concurrently access and modify a set. The first thread creates a hash set filled with numbers, and adds a new number to the set every second. The second thread obtains an iterator for the set and traverses the set back and forth through the iterator every second. You will receive a ConcurrentModificationException because the underlying set is being modified in the first thread while the set in the second thread is being traversed.


import java.util.HashSet;
import java.util.Iterator;

public class Exercise09 {

 public static HashSet<Integer> set = new HashSet<>();

 public static void main(String[] args) {
  new Thread1();
  new Thread2();
 }

 static class Thread1 implements Runnable {

  public Thread1() {
   Thread thread = new Thread(this);
   thread.start();
  }

  @Override
  public void run() {
   for (int i = 0; i < 10000000; i++) {
    set.add(i);
   }
  }
 }
 
 static class Thread2 implements Runnable {

  public Thread2() {
   Thread thread = new Thread(this);
   thread.start();
  }

  @Override
  public void run() {
   try {
    while (true) {
     for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) {
      iterator.next();      
     }     
     Thread.sleep(1000);
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

No comments :

Post a Comment