Groovy Goodness: Interrupted Sleeping

Groovy adds a lot of useful methods to the Java JDK classes. One of them is the sleep method that is added to all objects. With the sleep method we can add a pause to our code. The sleep method accepts a sleep time in milli seconds. The implementation of the method will always wait for he given amount of milli seconds even if interrupted. But we can add a closure as extra argument, which is invoked when the sleep method is interrupted. We should return true for the closure to really interrupt, otherwise we use false.

In the following example we use the sleep method to pause the bedtime method of the User class. We run the bedtime method in a thread and after 2000 milli seconds we intercept the thread. The sleep method still wait for 5 seconds, before ending:

When we run this script we get the following output:

Next we use the sleep method with a closure. The closure prints a message and return false, so the sleep method still only ends after 5 seconds:

Let’s run this script and we see the output from the closure we passed to the sleep method:

Finally we use a closure as argument for the sleep method, but this time we return true to indicate the sleep method must stop:

When we run this script we notice we are awake after 2 seconds:

Written with Groovy 2.4.7.

Original blog post

This entry was posted in Coding, Groovy and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *