Link to home
Start Free TrialLog in
Avatar of sciuriware
sciuriware

asked on

Runtime.addShutDownHook() prefers Thread above Runnable

///////////I was puzzled when my code was refused by the compiler:
public class X implements Runnable
{
    public void run() { ..... }    // What ever when it dies.
    private X(){}                    //  Don't create objects.
    public static void action()  // One of the methods, not instantiating this class.
    {
         Runtime.getRuntime().addShutdownHook(new X());  // Last will ....
    }
}
///////Things got better with :
public class X extends Thread
....
//////I should understand this but the coin won't drop this morning.
Avatar of girionis
girionis
Flag of Greece image

 What's the error message?
Avatar of sciuriware
sciuriware

ASKER

Cut from the ECLIPSE error window:
Error
  The method addShutdownHook(Thread) in the type Runtime is not applicable for the arguments (X)      X.java      GoiDo/RiengTu      line 125

Don't be confused by the package name.
;JOOP!
It seems that addShutdownHook requires a Thread as a parameter.  It must need some of the facilities provided by a Thread, otherwise the parameter would be a Runnable (as you originally tried).

The method can't down-cast your Runnable to a Thread.
 Weird... Can you try and cast X to Thread?
No, can't cast.
;JOOP!
 If all else fails use an inner thread class.
 Can't you do:

Runnable x = new X();
Thread t = (Thread) x;
Runtime.getRuntime().addShutdownHook(x);
 Ehm.. sorry I meant:

Runnable x = new X();
Runtime.getRuntime().addShutdownHook((Thread) x);
No girionis, you can't cast a Runnable to a Thread.
Did you check your advises in advance?
;JOOP!
 I didn't actually. I thought the compiler would accept it (I should go back to reading simple OO concepts I guess :( )... anyway just use an inner Thread class:

Runtime.getRuntime().addShutdownHook(new Thread() {...});
ASKER CERTIFIED SOLUTION
Avatar of jimmack
jimmack

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As I prefer to extend my classes or to implement on them (access to variables) I accept that I must extend from Thread.
Although the answer did not explain everything I guess jimmack kept to the rules and facts of JAVA. And 50 points is not much in these days ....
;JOOP!
;-)

Thanx.
 Actually this:

>Runnable x = new X();
>Runtime.getRuntime().addShutdownHook((Thread) x);

  *compiles perfectly* even though it throws a run-time error. ;-)
That's because the compiler assumes (in this case, falsely ;-)) that if you're forcing a cast, you know what you're doing ;-)
Thank you girionis, although you can't make me happy with runtime errors .......
;JOOP!
 jimmack true, I just thought sciuriware meant a compile-time error.