groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Keith Suderman <suder...@anc.org>
Subject Re: Unknown type: METHOD_DEF
Date Fri, 05 Jan 2018 22:17:58 GMT
What error are you seeing?  Do you see the error at runtime or in your IDE?  Your code works
for me (Groovy 2.4.9) so maybe check for unbalanced braces elsewhere in your code.

However, you shouldn't catch/rethrow the InterruptedException as you do. The InterruptedException
is not thrown for "some reason", it is thrown when another thread calls Thread.interrupt()
on your thread (e.g. to wake your thread up so it can check its state).  For example:

Thread t = Thread.start {
	boolean running = true
	while (running) {
		doSomeWork()
		try {
			Thread.sleep(1000) 
		}
		catch (InterruptedException e) {
			running = shouldIKeepRunning()
			return true
		}
	}
}
// At program shutdown/cleanup
t.interrupt()
t.join()
println "Our thread has termintated."

The Closure passed to the Thread.sleep method can be used in place of the try/catch block.
 That is the closure will be called when Thread.interrupt() is called on your thread i.e.:

	Thread t = Thread.start {
		boolean running = false
		while(running) {
			doSomeWork()
			Thread.sleep(1000) {
				// Called then Thread.sleep() is interrupted.
				running = false
				return true
			}
		}
	}
	// ...
	t.interrupt()
	t.join()


Finally, if you are doing complicated threading work you should really be using GPars or Java's
Executors, ThreadPools, et al.

Cheers,
Keith

> On Jan 5, 2018, at 11:01 AM, Mohan Radhakrishnan <radhakrishnan.mohan@gmail.com>
wrote:
> 
> 
> 
> 
> Hi,
>          I am new to groovy. Here I tried to create
> a simple wrapper around 'sleep'.
> I see the error in the subject at 'def'. What's wrong ?
> Thanks,
> Mohan
> 
> /**
>  * Our custom sleep logic.
>  */
> trait ThreadSleeper {
>      long ms
>      Closure cl = {}
> 
>     /*Sleep with an action taken*/
>     def  sleeperWithAction() {
>         try{
> 
>             Thread.sleep ms, cl
> 
>         }catch( InterruptedException ie ){
>             throw new SleepInterruptedException( ie, "Thread.sleep is interrupted for
"+
>                                                       "some reason [" + ie.getMessage()
+"]");
>         }
>     }
> 
> 
>     /*If there is no action to be taken then we call this*/
>     def  sleeper() {
>         try{
> 
>             Thread.sleep ms
> 
>         }catch( InterruptedException ie ){
>             throw new SleepInterruptedException( ie, "Thread.sleep is interrupted for
"+
>                                                      "some reason [" + ie.getMessage()
+"]");
>         }
>     }
> }

----------------------
Keith Suderman
Research Associate
Department of Computer Science
Vassar College, Poughkeepsie NY
suderman@cs.vassar.edu





Mime
View raw message