2

I am using jetty server to receive calls from http clients.

I am using BufferedWriter object to write a log file for debugging.

The server is always running in order to receive calls.

How can i tell the program to only close the stream (log_file.close) when the server stops?

I am not supposed to stop the server, but before the program terminates (when i touch the terminate button for example) how can i close the stream file in that point?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Michael A
  • 5,770
  • 16
  • 75
  • 127
  • Where are you using BufferedWriter object? Inside some web application on Jetty? – hakyer Feb 19 '12 at 08:42
  • I am using it in my Startup class as an object of the class (Startup contains my main method and i am init it in this main : _logWriter = new BufferedWriter(new FileWriter("log_file.txt")); – Michael A Feb 19 '12 at 08:44
  • So, if I understood you correctly - you want to listen if some other process was terminated? – hakyer Feb 19 '12 at 08:49
  • When the server process terminates, but the question is if it will even be relevent to the Bufferedstream object which is created and used in the main process (not part of the server) – Michael A Feb 19 '12 at 09:11

2 Answers2

3

If your code is running inside a web application (aka war) you can (and it's actually a best practice) to implement ServletContextListener and register it in your web.xml.

In contextInitialized you can make the necessary init operations.

In contextDestroyed you can close the stream.

Tarlog
  • 10,024
  • 2
  • 43
  • 67
3

If you are running Jetty embedded, then you have a couple of options.

You haven't indicated which version of Jetty, so I can't give you exact code for it, but your options are:

  • Register a "LifeCycle" object in the server, and implement a stop method in that lifecycle object that closes your log file. (Using something like addLifeCycle or addBean, depending on your Jetty version)

  • Add a shutdown thread in the JVM (Runtime.addShutdownHook)

Tim
  • 6,406
  • 22
  • 34