DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Why and How To Integrate Elastic APM in Apache JMeter
  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Trending

  • Implementing Secure API Gateways for Microservices Architecture
  • Google Cloud AI Agents With Gemini 3: Building Multi-Agent Systems That Actually Work
  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • How to Implement AI Agents in Rails With RubyLLM
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Interrupted Sleeping

Groovy Goodness: Interrupted Sleeping

The sleep method is explained with the use of closures. See how the sleep method works and how you can use interrupts to wake your code up when you want to.

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Oct. 25, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
27.0K Views

Join the DZone community and get the full member experience.

Join For Free

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 milliseconds. The implementation of the method will always wait for the given amount of milliseconds, even if interrupted. But we can add a closure as an 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.

Image title

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 milliseconds, we intercept the thread. The sleep method still waits for 5 seconds, before ending:

class User {
    String username

    void bedtime() {
        long start = System.currentTimeMillis()
        println 'Sleeping'
        sleep(5000)
        long slept = System.currentTimeMillis() - start
        println "Awake after $slept ms"
    }
}

def user = new User(username: 'mrhaki')

// Run bedtime method in thread.
def bedtime = Thread.start {
    user.bedtime()
}

def alarm = new Timer()
alarm.runAfter(2000) {
    println 'BEEP BEEP'
    // Interrupt thread with bedtime method.
    bedtime.interrupt()
}

bedtime.join()

When we run this script, we get the following output:

$ groovy user.groovy
Sleeping
BEEP BEEP
Awake after 5002 ms
$

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

class User {
    String username

    void bedtime() {
        long start = System.currentTimeMillis()
        println 'Sleeping'
        sleep(5000) { e ->
            assert e in InterruptedException
            println 'What is that noise?'
            false // keep on sleeping       
        }
        long slept = System.currentTimeMillis() - start
        println "Awake after $slept ms"
    }
}

def user = new User(username: 'mrhaki')

// Run bedtime method in thread.
def bedtime = Thread.start {
    user.bedtime()
}

def alarm = new Timer()
alarm.runAfter(2000) {
    println 'BEEP BEEP'
    // Interrupt thread with bedtime method.
    bedtime.interrupt()
}

bedtime.join()

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

$ groovy user.groovy
Sleeping
BEEP BEEP
What is that noise?
Awake after 5005 ms
$

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

class User {
    String username

    void bedtime() {
        long start = System.currentTimeMillis()
        println 'Sleeping'
        sleep(5000) { e ->
            assert e in InterruptedException
            println 'Yeah, yeah, I am awake...'
            true // stop on sleeping       
        }
        long slept = System.currentTimeMillis() - start
        println "Awake after $slept ms"
    }
}

def user = new User(username: 'mrhaki')

// Run bedtime method in thread.
def bedtime = Thread.start {
    user.bedtime()
}

def alarm = new Timer()
alarm.runAfter(2000) {
    println 'BEEP BEEP'
    // Interrupt thread with bedtime method.
    bedtime.interrupt()
}

bedtime.join()

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

$ groovy user.groovy
Sleeping
BEEP BEEP
Yeah, yeah, I am awake...
Awake after 2001 ms
$
Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Why and How To Integrate Elastic APM in Apache JMeter
  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook