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
Newsletter
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

  • How to Migrate From C/C++ to Rust: A Practical Guide for Embedded IoT Systems
  • Why AI Agents Need a Shared Enterprise Ontology
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • The SDLC After AI

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Oct. 25, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
27.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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