Note that there are some explanatory texts on larger screens.

plurals
  1. POExecuting a simple task on another thread in scala
    primarykey
    data
    text
    <p>I was wondering if there was a way to execute very simple tasks on another thread in scala that does not have a lot of overhead?</p> <p>Basically I would like to make a global 'executor' that can handle executing an arbitrary number of tasks. I can then use the executor to build up additional constructs.</p> <p>Additionally it would be nice if blocking or non-blocking considerations did not have to be considered by the clients. </p> <p>I know that the scala actors library is built on top of the Doug Lea FJ stuff, and also that they support to a limited degree what I am trying to accomplish. However from my understanding I will have to pre-allocate an 'Actor Pool' to accomplish.</p> <p>I would like to avoid making a global thread pool for this, as from what I understand it is not all that good at fine grained parallelism.</p> <p>Here is a simple example:</p> <pre><code>import concurrent.SyncVar object SimpleExecutor { import actors.Actor._ def exec[A](task: =&gt; A) : SyncVar[A] = { //what goes here? //This is what I currently have val x = new concurrent.SyncVar[A] //The overhead of making the actor appears to be a killer actor { x.set(task) } x } //Not really sure what to stick here def execBlocker[A](task: =&gt; A) : SyncVar[A] = exec(task) } </code></pre> <p>and now an example of using exec:</p> <pre><code>object Examples { //Benchmarks a task def benchmark(blk : =&gt; Unit) = { val start = System.nanoTime blk System.nanoTime - start } //Benchmarks and compares 2 tasks def cmp(a: =&gt; Any, b: =&gt; Any) = { val at = benchmark(a) val bt = benchmark(b) println(at + " " + bt + " " +at.toDouble / bt) } //Simple example for simple non blocking comparison import SimpleExecutor._ def paraAdd(hi: Int) = (0 until hi) map (i=&gt;exec(i+5)) foreach (_.get) def singAdd(hi: Int) = (0 until hi) foreach (i=&gt;i+5) //Simple example for the blocking performance import Thread.sleep def paraSle(hi : Int) = (0 until hi) map (i=&gt;exec(sleep(i))) foreach (_.get) def singSle(hi : Int) = (0 until hi) foreach (i=&gt;sleep(i)) } </code></pre> <p>Finally to run the examples (might want to do it a few times so HotSpot can warm up):</p> <pre><code>import Examples._ cmp(paraAdd(10000), singAdd(10000)) cmp(paraSle(100), singSle(100)) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload