1

i get an exception when i run my Main Class :exception on Thread's

i using run method, and it look like this :

    @Override
public synchronized void run() {
    // TODO Auto-generated method stub
    int randomNum = ThreadLocalRandom.current().nextInt(1, 4);
    Student studentThread = new Student();
    Inlay inlayThread = new Inlay();
    studentThread.setId(counter);
    inlayThread.setInlayId(randomNum);
    Course courseThread = new Course();
    courseThread.setInlayD(inlayThread);
    courseThread.setStudentD(studentThread);
    this.arrCourse.add(courseThread);
    System.out.println(courseThread.toString());
    counter++;
}

and my Main :

    Course c = new Course();
    for(int i = 0 ; i<200;i++)
    {
        Thread t = new Thread(c);
        t.start();
    }
    c.toString();

what is tihs exception say ?

thanks !

idan
  • 69
  • 1
  • 7

2 Answers2

0

You're trying to add items to an ArrayList at the same time using different threads. You will have to use a concurrent data structure (or use different lists, them merge them to together.)

You can find more about concurrent lists here: Is there a concurrent List in Java's JDK?

EDToaster
  • 3,160
  • 3
  • 16
  • 25
0

You try to add the items to (I guess) a common implementation ArrayList or List which is not thread safe and causes the ConcurrentModificationException which is thrown upon modifying (add/delete) a structure on which is not optimized to do so.

I recommend using the Collections.synchronizedList wrapper:

Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.

List<Course> arrCourse = Collections.synchronizedList(new ArrayList<>());
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • now it work ! but why ? this code say to 2 thread to not using the same pleace (like index 1 ) at the same time ? – idan Jun 03 '19 at 18:20
  • See the documentation of the [`ConcurrentModificationException`](https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html). The point is the exception is rather thrown than risk a non-deterministic behavior. – Nikolas Charalambidis Jun 03 '19 at 18:29
  • i thinkg my english no soo good to understand your link.. i'll try get help from my friends, thanks alot ! – idan Jun 03 '19 at 18:39