Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown hook doesn't work in Eclipse [duplicate]

I have added a shutdown hook via:

Runtime.getRuntime().addShutdownHook(myShutdownHook); 

It works fine normally, but not when I click the red stop button in Eclipse. Is there a way to make the shutdown hook be called in Eclipse?

like image 692
urir Avatar asked Oct 11 '12 09:10

urir


People also ask

How do I stop multiple Eclipse servers?

before launching, press ctrl-F2 . This shortcut terminates the currently running/debugged application.

How do I close spring boot in Eclipse?

Execute spring-boot:run via an Eclipse maven build run configuration. Hit the "Terminate" button on Eclipse's "Console" view.

How do I run multiple instances of a program in Eclipse?

The command line arguments are stored in Eclipse in a Run Configuration (menu: Run > Run Configurations... , or Run > Debug Configurations... ). Just create two of them, reference the same main class, and specify different command line arguments, e.g. to specify different ports, then Run / Debug both of them.


2 Answers

The red stop button forcibly kills the application, i.e. not gracefully, so the JVM doesn't know that the application is exiting, therefore the shutdown hooks are not invoked.

Unfortunately, there is no way (in Windows, at least) to provide a mechanism that ensures that the hook is always invoked. It's just something that may be invoked, but there is no guarantee.

like image 183
Zoltán Avatar answered Sep 21 '22 10:09

Zoltán


I made a hack by replacing JavaProcess with decorated one:

    IProcess p = launch.getProcesses()[0];     launch.addProcess(new JavaProcessDecorator(p));     launch.removeProcess(p); 

And decorator is overriding terminate function.

public class JavaProcessDecorator implements IProcess {  private IProcess p;  public JavaProcessDecorator(IProcess p) {     this.p = p; }  private boolean sigkill = false;  @SuppressWarnings("rawtypes") @Override public Object        getAdapter(Class arg)                { return p.getAdapter(arg); } ... @Override public ILaunch       getLaunch()                          { return p.getLaunch(); } @Override public IStreamsProxy getStreamsProxy()                    { return p.getStreamsProxy(); } @Override public void          setAttribute(String s1, String s2)   {        p.setAttribute(s1, s2); } @Override public void          terminate() throws DebugException    {     if(!sigkill) {         try {             IDebugIService cs = DirmiServer.INSTANCE.getRemote("main", IDebugIService.class);             if(cs != null) cs.modelEvent(new TerminateRequest());         } catch (RemoteException e) { }         this.sigkill = true;     } else p.terminate(); }} 

At first click on red button, I send a message to application asking for gently termination. If it is not working, second click on red button will kill it.

like image 26
Marek Jagielski Avatar answered Sep 23 '22 10:09

Marek Jagielski