13 February 2010

Groovy way to see if thread execution had errors

1 comment:
I had to write a script that did something and for a faster run I decided to use threads.
I needed to start a thread to do some task and then to be able to check that it had finished without an error/exception.
In Java if the code executed in a new thread throws an error, it doesn't matter that much, it just executes the next instruction after thread.join().
Some solutions found on the internet were
  • to put all the code inside the thread in a try-catch block and in the catch block populate a map with the thread name and status. Then you could get the status by querying statusMap[threadName]
  • add a status status field to your class witch is a subclass of Thread. Then you do the same thing as above and in the catch block modify the status to failed (status is successfull in the begining). You get get the status by thread.status
Luckily in  groovy we have dynamic object behaviour.
So my solution is to add a new field to the Thread class, and use Thread.setDefaultUncaughtExceptionHandler to populate it.
It looks something like
Thread.metaClass.failed = false

Thread.setDefaultUncaughtExceptionHandler(
        {t, ex ->
          t.failed = true
        } as Thread.UncaughtExceptionHandler)

def th= Thread.start {
  println ' in thread 1'
  throw new RuntimeException("thread exception")
  println ' in thread 2'

}
th.join()

assert th.failed

And now I can see if any exception/error has been thrown. And all the threads I start will have this property.

04 February 2010

Religions with a sense of humor

No comments:
I just love it when a religion has a sense of humor.
Discordianists are my favorite.
Today I came across The TriPrimality from subgenius:

The TriPrimality:
"Bob" is.
"Bob" becomes.
"Bob" is not.
Nothing is; Nothing becomes; Nothing is not. Thus: Nothing Is Everything.
  Therefore: Everything is "Bob."
Abracadabra.

"I don't practice what I preach, because I'm not the kind of person I'm preaching to."--Bob
You have to admit that is funny.
And I can't close without mentioning my favorite religious person, Robert Anton Wilson.

"Spectacles, testicles, brandy, cigars -- you're all popes! You're all absolutely infallible. I have the authority to appoint anyone a Discordian Pope, because I'm a Discordian Pope. The first rule after you become a Discordian Pope is to excommunicate every Discordian Pope you meet. This is based on the basic Discordian principle that we Discordians must stick apart."  - RAW

so, what can I say ?

"Spectacles, testicles, brandy, cigars -- you're all popes! "