Reputation: 14399
I want to close all FileHandler
s 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.
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) {}
}
}
}
Upvotes: 2
Views: 3921
Reputation: 168
Since you are adding handler using addHandler(), clean way is to close() and then call 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!
Upvotes: 2