Skip to content

Instantly share code, notes, and snippets.

@vaclav
Created September 10, 2014 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaclav/c93225b2f93263bb8c55 to your computer and use it in GitHub Desktop.
Save vaclav/c93225b2f93263bb8c55 to your computer and use it in GitHub Desktop.
Illustrates use of Groovy traits to safely start a thread through the run() method instead of the proper start() method
trait SafeStarter {
private boolean started = false
public void run() {
if (!started) {
this.start()
started = true
}
super.run()
}
}
println "Main thread: ${Thread.currentThread()}"
def t = new Thread({println "Running in ${Thread.currentThread()}"}).withTraits SafeStarter
t.run() //This is normally a mistake, start() should be called on a thread to start running asynchronously
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment