-1

I have created this simple worker thread to calculate palindromes by iterating through an ArrayList. I get an Error when I execute line temp_str1 = it.next();. The ArrayList buffer_List is not used by any other thread hence using synchronized block does not help. I have looked through previous questions and they did not help much. I would eager to find the solution to this problem.

Here is My code:

private void find_Palindromes(ArrayList<String> buffer_List){
    Iterator<String> it = buffer_List.iterator();
    String temp_str1, temp_str2;
    while(it.hasNext()){
        temp_str1 = it.next();
        //System.out.println(temp_str1);
        it.remove();

        if(is_Palindrome(temp_str1)){
            to_Shared_Queue(temp_str1);
            palin_count++;
        }
    }
}

Edit Code : added to_Shared_Queue

  private void to_Shared_Queue(String str){           
        synchronized(shared_queue){
            Shared_queue.add(str);
        }
  }
Muhammad Ali Qadri
  • 606
  • 2
  • 8
  • 21
  • Your [mcve] please. – Hovercraft Full Of Eels Oct 01 '16 at 20:36
  • Look at this guy's answer, might help you out. It's the remove method you're using to remove the item from the ArrayList. http://stackoverflow.com/questions/15993356/how-iterators-remove-method-actually-remove-an-object – kevto Oct 01 '16 at 20:36
  • 2
    I bet you are modifying buffer_List in to_Shared_Queue method. – MGorgon Oct 01 '16 at 20:38
  • @MGorgon: that's my bet too, but who the hell really knows for sure. – Hovercraft Full Of Eels Oct 01 '16 at 20:39
  • @MGorgon I am only sending the string temp_str1 within the parameter of to_Shared_Queue hence the list is not modified. – Muhammad Ali Qadri Oct 01 '16 at 20:41
  • Sorry, objects (anything that is not a primitive) such as lists are passed _by reference_, so there's only one copy and you are modifying the _same_ object. See this canonical question http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Jim Garrison Oct 01 '16 at 20:43
  • could you add your `to_Shared_Queue` method then? if the list is not modified there, maybe the list is still somehow accessed concurrently... – user140547 Oct 01 '16 at 20:48
  • You are modifying the ArrayList somehow while iterating through it. You need to find out how, by inspecting the method that you're not showing likely. – Hovercraft Full Of Eels Oct 01 '16 at 20:55
  • If Shared_queue is this same list as buffer_List then you have answer what's wrong. – MGorgon Oct 01 '16 at 22:22

1 Answers1

-2

It is because of you modifying iterator while looping over it . you can do it by remove it from your array buffer_List. buffer_List.remove(temp_str1);

jdev
  • 5,304
  • 1
  • 17
  • 20