You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Dyllon Michel Gagnier (Jira)" <ji...@apache.org> on 2022/08/18 16:30:00 UTC

[jira] [Created] (LANG-1690) Add function to convert forEach style functions to iterators

Dyllon Michel Gagnier created LANG-1690:
-------------------------------------------

             Summary: Add function to convert forEach style functions to iterators
                 Key: LANG-1690
                 URL: https://issues.apache.org/jira/browse/LANG-1690
             Project: Commons Lang
          Issue Type: Improvement
          Components: lang.*
            Reporter: Dyllon Michel Gagnier
         Attachments: Main.java

I had an idea to implement a function that converts from Consumer<Consumer<T>> (such as ArrayList::forEach) to Iterator<T> (or Iterable<T>). This can be done by running the forEach function in a separate thread and pausing the thread until .next() is called on the iterator (using a semaphore or await/notify, obviously not using Thread.suspend).

This seems very useful as a utility in cases where performance of iteration is not critical (since obviously switching thread contexts is expensive even with virtual threads) since it's essentially generators in pure Java.

I attached an example implementation that uses virtual threads, but platform threads can just as easily be used. Note that semaphores are used in this case instead of wait/notifyAll because the latter pins virtual threads (and thus would not be able to run on top of a single platform thread thereby defeating the whole point of virtual threads). To run the example, "--enable-preview" is needed since virtual threads are still in preview.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)