Groovy threads

Author: Chris Broadfoot
Posted on 6 August, 2008

I was just mucking about with threading in Groovy, it really is very simple. You pass Thread.start() a Closure. You could do something as simple as this:

Thread.start {
  // do expensive operation
}

Here’s the sample code I ended up with. There are a few semi-advanced Groovy concepts here.

ReentrantLock.metaClass.withLock allows us to give all ReentrantLock instances a new method called withLock. All this does is wrap a closure (which is called by it() in the middle) with the lock.

We then define a closure called worker, that prints out some spacing depending on which thread is working (the thread number is passed in as a parameter), and some dots, and the relative time (from when we started the program).

After this definition, we actually start 5 threads off, and print “ROCK!”. The curry method is very interesting, if you don’t know what it means, you should read more about currying.

The output of the code is below the sample code.

import java.util.concurrent.locks.ReentrantLock

def startTime = System.currentTimeMillis()

ReentrantLock.metaClass.withLock = {
  lock()
  try {
    it()
  }
  finally {
      unlock()
  }
}

def lock = new ReentrantLock()

def worker = { threadNum ->
  4.times { count ->
    lock.withLock {
      print " " * threadNum
      print "." * (count + 1)
      println " ${System.currentTimeMillis() - startTime}"
    }
    Thread.sleep(100);
  }
}

5.times {
  Thread.start worker.curry(it)
}

Output:

ROCK!
 . 6
  . 6
. 6
   . 7
    . 8
 .. 107
  .. 107
   .. 108
.. 108
    .. 109
 ... 208
   ... 208
  ... 209
    ... 209
... 210
 .... 311
  .... 311
    .... 312
   .... 312
.... 313