Arya
Arya

Reputation: 8985

gracefully ending a console based multi threaded program

I have a multi threaded console application which runs endlessly. Right now I use ctrl-c to end it, but sometimes it causes the finally block not to be called and leaves some processes that the original program started to run even after the main java program has ended.

I found this answer on Stackoverflow

https://stackoverflow.com/a/3194586/492015

class MyThread extends Thread
{
  volatile boolean finished = false;

  public void stopMe()
  {
    finished = true;
  }

  public void run()
  {
    while (!finished)
    {
      //do dirty work
    }
  }
}

But since my program is console based, how would this apply? I would need to make the program wait for keyboard inputs? so if I press 'q' for example stopMe() would get called. How would I have to do this?

Upvotes: 0

Views: 53

Answers (2)

Daniel Bauer
Daniel Bauer

Reputation: 138

If you want to clean up, you might want to consider a shutdown hook. See: Java shutdown hook

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100219

If you want to perform clean-up, you can register a shutdown hook:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        // do the cleanup
    }
});

According to my experience it's always executed when Ctrl+C is pressed.

Upvotes: 1

Related Questions