<%bte.doc super="item.bte" %>
<%bte.tpl name=pageTitle%>Parallelizer<%/bte.tpl%>
<%bte.tpl name=description%>Runs multiple jobs in parallel, n threads at a time, and waits until all threads are complete before continuing.<%/bte.tpl%>
<%bte.tpl name=keywords%>parallel execution, parallel threads, thread utility<%/bte.tpl%>
<%bte.tpl name=content%>

<div class=examplecode><h3>Example</h3>
<pre><span class=identifier>Parallelizer pll </span><span class=operator>= </span><span class=reservedWord>new </span><span class=identifier>Parallelizer</span><span class=separator>();
</span><span class=reservedWord>for </span><span class=separator>(</span><span class=reservedWord>int </span><span class=identifier>i</span><span class=operator>=</span><span class=literal>0</span><span class=separator>; </span><span class=identifier>i</span><span class=operator>&lt;</span><span class=literal>10</span><span class=separator>; </span><span class=identifier>i</span><span class=operator>++</span><span class=separator>){
    </span><span class=reservedWord>final int </span><span class=identifier>j </span><span class=operator>= </span><span class=identifier>i</span><span class=separator>;
    </span><span class=identifier>pll</span><span class=separator>.</span><span class=identifier>run</span><span class=separator>(
        </span><span class=reservedWord>new </span><span class=identifier>Runnable</span><span class=separator>(){
            </span><span class=identifier>System</span><span class=separator>.</span><span class=identifier>out</span><span class=separator>.</span><span class=identifier>println</span><span class=separator>(</span><span class=literal>&quot;Hello World &quot; </span><span class=operator>+ </span><span class=identifier>j</span><span class=separator>);
        }
    );
}
</span><span class=identifier>pll</span><span class=separator>.</span><span class=identifier>join</span><span class=separator>();
</span></pre>
</div>


<p>The Parallelizer class is a Java thread utility that allows one to easily convert their serial code to parallel code.  The class would typically be used to execute each iteration of a loop at once rather than one after another.  Good candidates for such an optimization would be when the order of execution does not matter and each iteration does slow operations such as sleeping or making network connections.</p>

<p>To use the Parallelizer, a developer would typically:</p>
<ol>
<li>Create a new Parallelizer before the loop.</li>
<li>Put the contents of the loop inside an in-line Runnable instance.</li>
<li>Copy all loop variables used inside the Runnable instance into finals</li>
<li>Call join() after the loop to wait until the threads are done and it is safe to proceed</li> 
</ol>



<p>[<a href="download.html">Download /w Source</a> |
<a href="Parallelizer.java.html">Browse Source</a> |
<a href="doc/com/Ostermiller/util/Parallelizer.html">Documentation</a>]</p>

<%/bte.tpl%>
<%/bte.doc%>
