Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2046

MethodClosure iterators could loop forever

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Won't Fix
    • 1.1-beta-2
    • None
    • groovy-jdk
    • None
    • Patch

    Description

      //generates an infinite sequence of Fibonacci numbers
      def fibonacci(Closure yield){
          def a=0
          def b=1
          def temp
          while(true){
              yield(b)
              temp=a
              a=b
              b=a+temp
          }
      }
      
      //BROKEN: the groovy runtime wants to run Fibonacci to termination, loading values into an array.
      //this generates an out of memory error, before ever calling the closure once.
       this.&fibonacci.find{it % 20 == 0}
      

      The proper solution is to use the attached Generator class that can properly invert control using threads, and only generates values on demand. I've also posted this solution at http://docs.codehaus.org/display/GROOVY/Iterator+Tricks for now, but it might be better to put it into the GDK.

      Attachments

        1. Generator.java
          5 kB
          Ken Bloom

        Issue Links

          Activity

            People

              Unassigned Unassigned
              kbloom Ken Bloom
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: