How to close FileHandlers in thread?

3.8k views Asked by At

I want to close all FileHandlers once the thread finished or was forcely finished.
I created a closeLogger function but it seems it's not being called
because I see that the file is still locked in the folder.

  1. What is the problem?
  2. Can I also handle it if I forcely terminated the execution in eclipse?

My code is as follows:

public class Passenger extends Thread {

    private Logger logger;

    public Passenger() throws SecurityException, IOException, InterruptedException {
        logger = Logger.getLogger(String.format("Passenger%sLogger", name));
        FileHandler fileHandler = new FileHandler(String.format(".\\Logs\\PassengerLogs\\passenger_%s.txt", name), true);
        fileHandler.setFormatter(new LogFormatter());
        logger.addHandler(fileHandler);
    }

    @Override
    public void run() {
        try {
            goToStation();
            waitForTaxi();
            if (passengerState == PassengerState.WatingInQueue) {
                goHome();
            } else { // already in taxi
                synchronized (this) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            closeLogger();
        }
    }

    private void closeLogger() {
        Logger logger = getLogger();
        java.util.logging.Handler[] handlers = logger.getHandlers();
        for (java.util.logging.Handler h : handlers) {
            try {
                h.close();
            } catch (SecurityException e) {}
        }
    }
}
1

There are 1 answers

1
spark07 On BEST ANSWER

Since you are adding handler using addHandler(), clean way is to close() and then call removeHandler()

See removeHandler

Also, copied from above link:

After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent's Handlers, recursively up the tree.

So if you are not removing handler, it will still hold reference. This may be the reason why your file is still locked. Try this and let me know if it works!