[concurrency-interest] Iterator does not work after removal of last element

Shyamal.Mehta at trilogy.com Shyamal.Mehta at trilogy.com
Thu May 12 01:56:05 EDT 2005


While using the LinkedBlockingQueue, I found the following behavior:

Once the remove method is called on the queue when only one element is 
present in it, the iterator returned by any subsequent calls to iterator() 
method (even after we have filled more elements in the queue), returns an 
iterator that behaves that the queue is empty.

I have attached the test program I wrote to verify this. Is it a bug or am 
I missing something?

The same behavior is shown when using JDK 1.5 too.

Thanks,
Shyamal




import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
import java.util.Iterator;

public class TestConcurrent 
{
        public static void main(String[] args) 
        {
        try
        {
            LinkedBlockingQueue q = new LinkedBlockingQueue();
            Integer data;
            Iterator iter;
            for (int i = 1; i <= 100 ; i++ )
            {

                data = new Integer(i);
                q.add(data);

                System.out.print("Inserted " + i + " th element. Queue 
size is " + q.size() + ". ");
                iter = q.iterator();
                int count = 0;
                while ( iter.hasNext() )
                {
                    iter.next();
                    count++;
                }
                System.out.println("Iterator found " + count + " elements. 
");
 
                /*
                Removing the element by either of the two ways (by the 
queue's 
                remove method or the iterator's remove method) results in 
an 
                iterator being returned (on the next call of iterator() 
method)
                that always behaves as if the queue is empty.
                If we use the queue's take method to remove elements, that 
works.
                */
                q.remove(data);

                /*iter = q.iterator();
                count = 0;
                while ( iter.hasNext() )
                {
                    iter.next();
                    iter.remove();
                    count++;
                }
                System.out.println(" Removed "+count+" elements.");*/
 
                //q.take();
 
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20050512/b8d39e49/attachment-0001.htm


More information about the Concurrency-interest mailing list