Java - Calling a method containing a forloop multiple times within a second leads to minimal blocking of main thread
<p>In our app, one of our interfaces has a color wheel. When the user drags his finger really fast, the callback for the color wheel color adjusting callback, <code>onColorChanged</code> will be called. Inside <code>onColorChanged</code> we have a forloop which loops around N times depending upon the number of speakers.  each time the callback is called. Inside the forloop, we are calling a method from a singleton which performs a task on a separate thread. Here's how the code looks:</p>

<pre><code>void onColorChanged
{
    for(int i = 0; i &lt; speakers.count)
    {
        //speaker connection is a thread which is kept alive as long as the connection between the app and the speaker is not terminated
        SpeakerConnection connection = SpeakerConnectionManager.getConnectionForSpeakerWithID(speakerID);

        connection.sendAdjustColorCommand(); 
    }
}
</code></pre>

<p>Now, obviously this is not our real code, but a big picture of how our code flows. <code>onColorChanged</code> will be called more than a hundred times depending on the speed of the user's dragging. </p>

<p>This causes the forloop to be called multiple times within a few seconds. We are suspecting that this is what causes the UI to be laggy because when we commented out the forloop, eveything goes smooth.</p>

<p>What we tried is:</p>

<pre><code>void onColorChanged
{
    new Thread(new Runnable()
    {
       for(int i = 0; i &lt; speakers.count)
       {
        //speaker connection is a thread which is kept alive as long as the connection between the app and the speaker is not terminated
           SpeakerConnection connection = SpeakerConnectionManager.getConnectionForSpeakerWithID(speakerID);

           connection.sendAdjustColorCommand(); 
       }
    }).start();
}
</code></pre>

<p>We will start a new thread everytime the <code>onColorChanged</code> is called. But we are afraid that this will consume a lot of memory, although we knew that threads that have done it's task will be killed automatically. But we see memory spikes from the memory analyzer and don't want this to happen.</p>

<p>So, my question is:</p>

<ol>
<li><p>Calling the forloop multiple times in main thread causes the UI to be laggy? I mean, it's just a loop of not more than 10 times as of now. If it's 10000 times then I think it would, but it's not.</p></li>
<li><p>If instantiating a new thread everytime the callback is called is really not a good thing to do, then is there any other way we can solve this?</p></li>
</ol>

<p>Thanks!</p>