Python generators in Java?

Daniel Dittmar daniel.dittmar at sap.corp
Mon Nov 15 11:46:39 EST 2004


Robert Oschler wrote:
> One of my favorite Python features is generators.  I have to use Java for
> one particular project (it happens).  I would like to have something at
> least close to Python's generators for the project.

Sketch:
- create a Queue class
- the 'generator' would run in a thread and put objects into the queue 
(equivalent to yield)
- the 'main' program would run in the main thread and consume objects 
from the queue (equivalent to calling generator.next ())
- the consumer must block if the queue is empty
- the producer must block if the number of objects in the queue exceeds 
a certain amount (queue size = 1 is perfectly acceptable unless the 
producer is I/O bound)
- if you use generators to walk recursive structures, then you probably 
need only one queue instead of one generator for each level.
- perhaps you can get away with one superclass that creates both queue 
and thread, the 'generator' could then be implemented as an anonymous class.

Daniel



More information about the Python-list mailing list