twilio / twilio-java

A Java library for communicating with the Twilio REST API and generating TwiML.
MIT License
484 stars 425 forks source link

ResourceSet will only iterate its elements once #684

Open rjbird77 opened 2 years ago

rjbird77 commented 2 years ago

Issue Summary

ResourceSet implement Iterable, but its implementation is flawed. You can only iterate through its elements once, even if you get a new iterator.

ResourceSet implements Iterable and has inner class ResourceSetIterator for its iterator internally. The implementation of ResourceSetIterator uses class variables from ResourceSet, specifically ResourceSet.iterator and ResourceSet.processed. Because of this, even though ResourceSet.iterator() method does create a new instance of ResourceSetIterator, since the processed count and the iterator in the outer class never get reset, it is functionally still at the end (hasNext() method returns false).

Steps to Reproduce

  1. Get a ResourceSet
  2. Iterate through the elements - works
  3. Iterate through the elements again - never goes into the loop

Code Snippet

import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.monitor.v1.Alert;

public class Example {
    public static void main(String[] args) {
        Twilio.init("my_account_sid", "my_auth_token");
        ResourceSet<Alert> alerts = Alert.reader().limit(5).read();

        System.out.println("Before first loop:");
        for(Alert record : alerts) {
            System.out.println("     First loop - " + record.getSid());
        }

        System.out.println("Before second loop:");
        for(Alert record : alerts) {
            System.out.println("     Second loop - " + record.getSid());
        }
        System.out.println("After second loop");
    }
}

Exception/Log

Output from above code - second loop had no output:

Before first loop:
     First loop - NO06bc5d5591ecd607e21f5f3436dc22b0
     First loop - NO48d74ff1f40c2ef88d4c74dbc0d39907
     First loop - NO27183f081d5903afb84ec8b5e3a1b7be
     First loop - NO8426237981e0ea63bab859157c1c9ca8
     First loop - NOc2ef3b0918b79d2a62a0efc8290a1885
Before second loop:
After second loop

Technical details:

claudiachua commented 2 years ago

Hi @rjbird77, this issue has been added to our internal backlog to be prioritized. Pull requests and +1s on the issue summary will help it move up the backlog.

JerinTheElite commented 6 months ago

The same issue in the latest Twilio Java SDK 10.1.0 as well. I'm using Java 17